database.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package database
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "encoding/json"
  6. "errors"
  7. "time"
  8. "github.com/google/uuid"
  9. "github.com/gravitl/netmaker/logger"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/servercfg"
  12. )
  13. // NETWORKS_TABLE_NAME - networks table
  14. const NETWORKS_TABLE_NAME = "networks"
  15. // NODES_TABLE_NAME - nodes table
  16. const NODES_TABLE_NAME = "nodes"
  17. // DELETED_NODES_TABLE_NAME - deleted nodes table
  18. const DELETED_NODES_TABLE_NAME = "deletednodes"
  19. // USERS_TABLE_NAME - users table
  20. const USERS_TABLE_NAME = "users"
  21. // DNS_TABLE_NAME - dns table
  22. const DNS_TABLE_NAME = "dns"
  23. // EXT_CLIENT_TABLE_NAME - ext client table
  24. const EXT_CLIENT_TABLE_NAME = "extclients"
  25. // INT_CLIENTS_TABLE_NAME - int client table
  26. const INT_CLIENTS_TABLE_NAME = "intclients"
  27. // PEERS_TABLE_NAME - peers table
  28. const PEERS_TABLE_NAME = "peers"
  29. // SERVERCONF_TABLE_NAME - stores server conf
  30. const SERVERCONF_TABLE_NAME = "serverconf"
  31. // SERVER_UUID_TABLE_NAME - stores
  32. const SERVER_UUID_TABLE_NAME = "serveruuid"
  33. // SERVER_UUID_RECORD_KEY - telemetry thing
  34. const SERVER_UUID_RECORD_KEY = "serveruuid"
  35. // DATABASE_FILENAME - database file name
  36. const DATABASE_FILENAME = "netmaker.db"
  37. // GENERATED_TABLE_NAME - stores server generated k/v
  38. const GENERATED_TABLE_NAME = "generated"
  39. // == ERROR CONSTS ==
  40. // NO_RECORD - no singular result found
  41. const NO_RECORD = "no result found"
  42. // NO_RECORDS - no results found
  43. const NO_RECORDS = "could not find any records"
  44. // == Constants ==
  45. // INIT_DB - initialize db
  46. const INIT_DB = "init"
  47. // CREATE_TABLE - create table const
  48. const CREATE_TABLE = "createtable"
  49. // INSERT - insert into db const
  50. const INSERT = "insert"
  51. // INSERT_PEER - insert peer into db const
  52. const INSERT_PEER = "insertpeer"
  53. // DELETE - delete db record const
  54. const DELETE = "delete"
  55. // DELETE_ALL - delete a table const
  56. const DELETE_ALL = "deleteall"
  57. // FETCH_ALL - fetch table contents const
  58. const FETCH_ALL = "fetchall"
  59. // CLOSE_DB - graceful close of db const
  60. const CLOSE_DB = "closedb"
  61. func getCurrentDB() map[string]interface{} {
  62. switch servercfg.GetDB() {
  63. case "rqlite":
  64. return RQLITE_FUNCTIONS
  65. case "sqlite":
  66. return SQLITE_FUNCTIONS
  67. case "postgres":
  68. return PG_FUNCTIONS
  69. default:
  70. return SQLITE_FUNCTIONS
  71. }
  72. }
  73. // InitializeDatabase - initializes database
  74. func InitializeDatabase() error {
  75. logger.Log(0, "connecting to", servercfg.GetDB())
  76. tperiod := time.Now().Add(10 * time.Second)
  77. for {
  78. if err := getCurrentDB()[INIT_DB].(func() error)(); err != nil {
  79. logger.Log(0, "unable to connect to db, retrying . . .")
  80. if time.Now().After(tperiod) {
  81. return err
  82. }
  83. } else {
  84. break
  85. }
  86. time.Sleep(2 * time.Second)
  87. }
  88. createTables()
  89. return initializeUUID()
  90. }
  91. func createTables() {
  92. createTable(NETWORKS_TABLE_NAME)
  93. createTable(NODES_TABLE_NAME)
  94. createTable(DELETED_NODES_TABLE_NAME)
  95. createTable(USERS_TABLE_NAME)
  96. createTable(DNS_TABLE_NAME)
  97. createTable(EXT_CLIENT_TABLE_NAME)
  98. createTable(INT_CLIENTS_TABLE_NAME)
  99. createTable(PEERS_TABLE_NAME)
  100. createTable(SERVERCONF_TABLE_NAME)
  101. createTable(SERVER_UUID_TABLE_NAME)
  102. createTable(GENERATED_TABLE_NAME)
  103. }
  104. func createTable(tableName string) error {
  105. return getCurrentDB()[CREATE_TABLE].(func(string) error)(tableName)
  106. }
  107. // IsJSONString - checks if valid json
  108. func IsJSONString(value string) bool {
  109. var jsonInt interface{}
  110. var nodeInt models.Node
  111. return json.Unmarshal([]byte(value), &jsonInt) == nil || json.Unmarshal([]byte(value), &nodeInt) == nil
  112. }
  113. // Insert - inserts object into db
  114. func Insert(key string, value string, tableName string) error {
  115. if key != "" && value != "" && IsJSONString(value) {
  116. return getCurrentDB()[INSERT].(func(string, string, string) error)(key, value, tableName)
  117. } else {
  118. return errors.New("invalid insert " + key + " : " + value)
  119. }
  120. }
  121. // InsertPeer - inserts peer into db
  122. func InsertPeer(key string, value string) error {
  123. if key != "" && value != "" && IsJSONString(value) {
  124. return getCurrentDB()[INSERT_PEER].(func(string, string) error)(key, value)
  125. } else {
  126. return errors.New("invalid peer insert " + key + " : " + value)
  127. }
  128. }
  129. // DeleteRecord - deletes a record from db
  130. func DeleteRecord(tableName string, key string) error {
  131. return getCurrentDB()[DELETE].(func(string, string) error)(tableName, key)
  132. }
  133. // DeleteAllRecords - removes a table and remakes
  134. func DeleteAllRecords(tableName string) error {
  135. err := getCurrentDB()[DELETE_ALL].(func(string) error)(tableName)
  136. if err != nil {
  137. return err
  138. }
  139. err = createTable(tableName)
  140. if err != nil {
  141. return err
  142. }
  143. return nil
  144. }
  145. // FetchRecord - fetches a record
  146. func FetchRecord(tableName string, key string) (string, error) {
  147. results, err := FetchRecords(tableName)
  148. if err != nil {
  149. return "", err
  150. }
  151. if results[key] == "" {
  152. return "", errors.New(NO_RECORD)
  153. }
  154. return results[key], nil
  155. }
  156. // FetchRecords - fetches all records in given table
  157. func FetchRecords(tableName string) (map[string]string, error) {
  158. return getCurrentDB()[FETCH_ALL].(func(string) (map[string]string, error))(tableName)
  159. }
  160. // initializeUUID - create a UUID record for server if none exists
  161. func initializeUUID() error {
  162. records, err := FetchRecords(SERVER_UUID_TABLE_NAME)
  163. if err != nil {
  164. if !IsEmptyRecord(err) {
  165. return err
  166. }
  167. } else if len(records) > 0 {
  168. return nil
  169. }
  170. var rsaPrivKey, keyErr = rsa.GenerateKey(rand.Reader, 2048)
  171. if keyErr != nil {
  172. return keyErr
  173. }
  174. data, _ := json.Marshal(rsaPrivKey)
  175. telemetry := models.Telemetry{UUID: uuid.NewString(), TrafficKey: string(data)}
  176. telJSON, err := json.Marshal(&telemetry)
  177. if err != nil {
  178. return err
  179. }
  180. return Insert(SERVER_UUID_RECORD_KEY, string(telJSON), SERVER_UUID_TABLE_NAME)
  181. }
  182. // CloseDB - closes a database gracefully
  183. func CloseDB() {
  184. getCurrentDB()[CLOSE_DB].(func())()
  185. }