database.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package database
  2. import (
  3. "crypto/rand"
  4. "encoding/json"
  5. "errors"
  6. "time"
  7. "github.com/google/uuid"
  8. "github.com/gravitl/netmaker/logger"
  9. "github.com/gravitl/netmaker/models"
  10. "github.com/gravitl/netmaker/netclient/ncutils"
  11. "github.com/gravitl/netmaker/servercfg"
  12. "golang.org/x/crypto/nacl/box"
  13. )
  14. // NETWORKS_TABLE_NAME - networks table
  15. const NETWORKS_TABLE_NAME = "networks"
  16. // NODES_TABLE_NAME - nodes table
  17. const NODES_TABLE_NAME = "nodes"
  18. // DELETED_NODES_TABLE_NAME - deleted nodes table
  19. const DELETED_NODES_TABLE_NAME = "deletednodes"
  20. // USERS_TABLE_NAME - users table
  21. const USERS_TABLE_NAME = "users"
  22. // DNS_TABLE_NAME - dns table
  23. const DNS_TABLE_NAME = "dns"
  24. // EXT_CLIENT_TABLE_NAME - ext client table
  25. const EXT_CLIENT_TABLE_NAME = "extclients"
  26. // PEERS_TABLE_NAME - peers table
  27. const PEERS_TABLE_NAME = "peers"
  28. // SERVERCONF_TABLE_NAME - stores server conf
  29. const SERVERCONF_TABLE_NAME = "serverconf"
  30. // SERVER_UUID_TABLE_NAME - stores unique netmaker server data
  31. const SERVER_UUID_TABLE_NAME = "serveruuid"
  32. // SERVER_UUID_RECORD_KEY - telemetry thing
  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. return initializeUUID()
  89. }
  90. func createTables() {
  91. createTable(NETWORKS_TABLE_NAME)
  92. createTable(NODES_TABLE_NAME)
  93. createTable(DELETED_NODES_TABLE_NAME)
  94. createTable(USERS_TABLE_NAME)
  95. createTable(DNS_TABLE_NAME)
  96. createTable(EXT_CLIENT_TABLE_NAME)
  97. createTable(PEERS_TABLE_NAME)
  98. createTable(SERVERCONF_TABLE_NAME)
  99. createTable(SERVER_UUID_TABLE_NAME)
  100. createTable(GENERATED_TABLE_NAME)
  101. }
  102. func createTable(tableName string) error {
  103. return getCurrentDB()[CREATE_TABLE].(func(string) error)(tableName)
  104. }
  105. // IsJSONString - checks if valid json
  106. func IsJSONString(value string) bool {
  107. var jsonInt interface{}
  108. var nodeInt models.Node
  109. return json.Unmarshal([]byte(value), &jsonInt) == nil || json.Unmarshal([]byte(value), &nodeInt) == nil
  110. }
  111. // Insert - inserts object into db
  112. func Insert(key string, value string, tableName string) error {
  113. if key != "" && value != "" && IsJSONString(value) {
  114. return getCurrentDB()[INSERT].(func(string, string, string) error)(key, value, tableName)
  115. } else {
  116. return errors.New("invalid insert " + key + " : " + value)
  117. }
  118. }
  119. // InsertPeer - inserts peer into db
  120. func InsertPeer(key string, value string) error {
  121. if key != "" && value != "" && IsJSONString(value) {
  122. return getCurrentDB()[INSERT_PEER].(func(string, string) error)(key, value)
  123. } else {
  124. return errors.New("invalid peer insert " + key + " : " + value)
  125. }
  126. }
  127. // DeleteRecord - deletes a record from db
  128. func DeleteRecord(tableName string, key string) error {
  129. return getCurrentDB()[DELETE].(func(string, string) error)(tableName, key)
  130. }
  131. // DeleteAllRecords - removes a table and remakes
  132. func DeleteAllRecords(tableName string) error {
  133. err := getCurrentDB()[DELETE_ALL].(func(string) error)(tableName)
  134. if err != nil {
  135. return err
  136. }
  137. err = createTable(tableName)
  138. if err != nil {
  139. return err
  140. }
  141. return nil
  142. }
  143. // FetchRecord - fetches a record
  144. func FetchRecord(tableName string, key string) (string, error) {
  145. results, err := FetchRecords(tableName)
  146. if err != nil {
  147. return "", err
  148. }
  149. if results[key] == "" {
  150. return "", errors.New(NO_RECORD)
  151. }
  152. return results[key], nil
  153. }
  154. // FetchRecords - fetches all records in given table
  155. func FetchRecords(tableName string) (map[string]string, error) {
  156. return getCurrentDB()[FETCH_ALL].(func(string) (map[string]string, error))(tableName)
  157. }
  158. // initializeUUID - create a UUID record for server if none exists
  159. func initializeUUID() error {
  160. records, err := FetchRecords(SERVER_UUID_TABLE_NAME)
  161. if err != nil {
  162. if !IsEmptyRecord(err) {
  163. return err
  164. }
  165. } else if len(records) > 0 {
  166. return nil
  167. }
  168. // setup encryption keys
  169. var trafficPubKey, trafficPrivKey, errT = box.GenerateKey(rand.Reader) // generate traffic keys
  170. if errT != nil {
  171. return errT
  172. }
  173. tPriv, err := ncutils.ConvertKeyToBytes(trafficPrivKey)
  174. if err != nil {
  175. return err
  176. }
  177. tPub, err := ncutils.ConvertKeyToBytes(trafficPubKey)
  178. if err != nil {
  179. return err
  180. }
  181. telemetry := models.Telemetry{
  182. UUID: uuid.NewString(),
  183. TrafficKeyPriv: tPriv,
  184. TrafficKeyPub: tPub,
  185. }
  186. telJSON, err := json.Marshal(&telemetry)
  187. if err != nil {
  188. return err
  189. }
  190. return Insert(SERVER_UUID_RECORD_KEY, string(telJSON), SERVER_UUID_TABLE_NAME)
  191. }
  192. // CloseDB - closes a database gracefully
  193. func CloseDB() {
  194. getCurrentDB()[CLOSE_DB].(func())()
  195. }