database.go 5.8 KB

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