database.go 6.0 KB

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