database.go 5.8 KB

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