database.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. // CERTS_TABLE_NAME - certificates table
  23. const CERTS_TABLE_NAME = "certs"
  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. // PEERS_TABLE_NAME - peers table
  29. const PEERS_TABLE_NAME = "peers"
  30. // SERVERCONF_TABLE_NAME - stores server conf
  31. const SERVERCONF_TABLE_NAME = "serverconf"
  32. // SERVER_UUID_TABLE_NAME - stores unique netmaker server data
  33. const SERVER_UUID_TABLE_NAME = "serveruuid"
  34. // SERVER_UUID_RECORD_KEY - telemetry thing
  35. const SERVER_UUID_RECORD_KEY = "serveruuid"
  36. // DATABASE_FILENAME - database file name
  37. const DATABASE_FILENAME = "netmaker.db"
  38. // GENERATED_TABLE_NAME - stores server generated k/v
  39. const GENERATED_TABLE_NAME = "generated"
  40. // NODE_ACLS_TABLE_NAME - stores the node ACL rules
  41. const NODE_ACLS_TABLE_NAME = "nodeacls"
  42. // == ERROR CONSTS ==
  43. // NO_RECORD - no singular result found
  44. const NO_RECORD = "no result found"
  45. // NO_RECORDS - no results found
  46. const NO_RECORDS = "could not find any records"
  47. // == Constants ==
  48. // INIT_DB - initialize db
  49. const INIT_DB = "init"
  50. // CREATE_TABLE - create table const
  51. const CREATE_TABLE = "createtable"
  52. // INSERT - insert into db const
  53. const INSERT = "insert"
  54. // INSERT_PEER - insert peer into db const
  55. const INSERT_PEER = "insertpeer"
  56. // DELETE - delete db record const
  57. const DELETE = "delete"
  58. // DELETE_ALL - delete a table const
  59. const DELETE_ALL = "deleteall"
  60. // FETCH_ALL - fetch table contents const
  61. const FETCH_ALL = "fetchall"
  62. // CLOSE_DB - graceful close of db const
  63. const CLOSE_DB = "closedb"
  64. func getCurrentDB() map[string]interface{} {
  65. switch servercfg.GetDB() {
  66. case "rqlite":
  67. return RQLITE_FUNCTIONS
  68. case "sqlite":
  69. return SQLITE_FUNCTIONS
  70. case "postgres":
  71. return PG_FUNCTIONS
  72. default:
  73. return SQLITE_FUNCTIONS
  74. }
  75. }
  76. // InitializeDatabase - initializes database
  77. func InitializeDatabase() error {
  78. logger.Log(0, "connecting to", servercfg.GetDB())
  79. tperiod := time.Now().Add(10 * time.Second)
  80. for {
  81. if err := getCurrentDB()[INIT_DB].(func() error)(); err != nil {
  82. logger.Log(0, "unable to connect to db, retrying . . .")
  83. if time.Now().After(tperiod) {
  84. return err
  85. }
  86. } else {
  87. break
  88. }
  89. time.Sleep(2 * time.Second)
  90. }
  91. createTables()
  92. return initializeUUID()
  93. }
  94. func createTables() {
  95. createTable(NETWORKS_TABLE_NAME)
  96. createTable(NODES_TABLE_NAME)
  97. createTable(CERTS_TABLE_NAME)
  98. createTable(DELETED_NODES_TABLE_NAME)
  99. createTable(USERS_TABLE_NAME)
  100. createTable(DNS_TABLE_NAME)
  101. createTable(EXT_CLIENT_TABLE_NAME)
  102. createTable(PEERS_TABLE_NAME)
  103. createTable(SERVERCONF_TABLE_NAME)
  104. createTable(SERVER_UUID_TABLE_NAME)
  105. createTable(GENERATED_TABLE_NAME)
  106. createTable(NODE_ACLS_TABLE_NAME)
  107. }
  108. func createTable(tableName string) error {
  109. return getCurrentDB()[CREATE_TABLE].(func(string) error)(tableName)
  110. }
  111. // IsJSONString - checks if valid json
  112. func IsJSONString(value string) bool {
  113. var jsonInt interface{}
  114. var nodeInt models.Node
  115. return json.Unmarshal([]byte(value), &jsonInt) == nil || json.Unmarshal([]byte(value), &nodeInt) == nil
  116. }
  117. // Insert - inserts object into db
  118. func Insert(key string, value string, tableName string) error {
  119. if key != "" && value != "" && IsJSONString(value) {
  120. return getCurrentDB()[INSERT].(func(string, string, string) error)(key, value, tableName)
  121. } else {
  122. return errors.New("invalid insert " + key + " : " + value)
  123. }
  124. }
  125. // InsertPeer - inserts peer into db
  126. func InsertPeer(key string, value string) error {
  127. if key != "" && value != "" && IsJSONString(value) {
  128. return getCurrentDB()[INSERT_PEER].(func(string, string) error)(key, value)
  129. } else {
  130. return errors.New("invalid peer insert " + key + " : " + value)
  131. }
  132. }
  133. // DeleteRecord - deletes a record from db
  134. func DeleteRecord(tableName string, key string) error {
  135. return getCurrentDB()[DELETE].(func(string, string) error)(tableName, key)
  136. }
  137. // DeleteAllRecords - removes a table and remakes
  138. func DeleteAllRecords(tableName string) error {
  139. err := getCurrentDB()[DELETE_ALL].(func(string) error)(tableName)
  140. if err != nil {
  141. return err
  142. }
  143. err = createTable(tableName)
  144. if err != nil {
  145. return err
  146. }
  147. return nil
  148. }
  149. // FetchRecord - fetches a record
  150. func FetchRecord(tableName string, key string) (string, error) {
  151. results, err := FetchRecords(tableName)
  152. if err != nil {
  153. return "", err
  154. }
  155. if results[key] == "" {
  156. return "", errors.New(NO_RECORD)
  157. }
  158. return results[key], nil
  159. }
  160. // FetchRecords - fetches all records in given table
  161. func FetchRecords(tableName string) (map[string]string, error) {
  162. return getCurrentDB()[FETCH_ALL].(func(string) (map[string]string, error))(tableName)
  163. }
  164. // initializeUUID - create a UUID record for server if none exists
  165. func initializeUUID() error {
  166. records, err := FetchRecords(SERVER_UUID_TABLE_NAME)
  167. if err != nil {
  168. if !IsEmptyRecord(err) {
  169. return err
  170. }
  171. } else if len(records) > 0 {
  172. return nil
  173. }
  174. // setup encryption keys
  175. var trafficPubKey, trafficPrivKey, errT = box.GenerateKey(rand.Reader) // generate traffic keys
  176. if errT != nil {
  177. return errT
  178. }
  179. tPriv, err := ncutils.ConvertKeyToBytes(trafficPrivKey)
  180. if err != nil {
  181. return err
  182. }
  183. tPub, err := ncutils.ConvertKeyToBytes(trafficPubKey)
  184. if err != nil {
  185. return err
  186. }
  187. telemetry := models.Telemetry{
  188. UUID: uuid.NewString(),
  189. TrafficKeyPriv: tPriv,
  190. TrafficKeyPub: tPub,
  191. }
  192. telJSON, err := json.Marshal(&telemetry)
  193. if err != nil {
  194. return err
  195. }
  196. return Insert(SERVER_UUID_RECORD_KEY, string(telJSON), SERVER_UUID_TABLE_NAME)
  197. }
  198. // CloseDB - closes a database gracefully
  199. func CloseDB() {
  200. getCurrentDB()[CLOSE_DB].(func())()
  201. }