database.go 6.0 KB

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