database.go 5.4 KB

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