database.go 6.7 KB

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