database.go 6.2 KB

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