database.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package database
  2. import (
  3. "crypto/rand"
  4. "encoding/json"
  5. "errors"
  6. "sync"
  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. const (
  16. // == Table Names ==
  17. // NETWORKS_TABLE_NAME - networks table
  18. NETWORKS_TABLE_NAME = "networks"
  19. // NODES_TABLE_NAME - nodes table
  20. NODES_TABLE_NAME = "nodes"
  21. // DELETED_NODES_TABLE_NAME - deleted nodes table
  22. DELETED_NODES_TABLE_NAME = "deletednodes"
  23. // USERS_TABLE_NAME - users table
  24. USERS_TABLE_NAME = "users"
  25. // CERTS_TABLE_NAME - certificates table
  26. CERTS_TABLE_NAME = "certs"
  27. // DNS_TABLE_NAME - dns table
  28. DNS_TABLE_NAME = "dns"
  29. // EXT_CLIENT_TABLE_NAME - ext client table
  30. EXT_CLIENT_TABLE_NAME = "extclients"
  31. // PEERS_TABLE_NAME - peers table
  32. PEERS_TABLE_NAME = "peers"
  33. // SERVERCONF_TABLE_NAME - stores server conf
  34. SERVERCONF_TABLE_NAME = "serverconf"
  35. // SERVER_UUID_TABLE_NAME - stores unique netmaker server data
  36. SERVER_UUID_TABLE_NAME = "serveruuid"
  37. // SERVER_UUID_RECORD_KEY - telemetry thing
  38. SERVER_UUID_RECORD_KEY = "serveruuid"
  39. // DATABASE_FILENAME - database file name
  40. DATABASE_FILENAME = "netmaker.db"
  41. // GENERATED_TABLE_NAME - stores server generated k/v
  42. GENERATED_TABLE_NAME = "generated"
  43. // NODE_ACLS_TABLE_NAME - stores the node ACL rules
  44. NODE_ACLS_TABLE_NAME = "nodeacls"
  45. // SSO_STATE_CACHE - holds sso session information for OAuth2 sign-ins
  46. SSO_STATE_CACHE = "ssostatecache"
  47. // METRICS_TABLE_NAME - stores network metrics
  48. METRICS_TABLE_NAME = "metrics"
  49. // NETWORK_USER_TABLE_NAME - network user table tracks stats for a network user per network
  50. NETWORK_USER_TABLE_NAME = "networkusers"
  51. // USER_GROUPS_TABLE_NAME - table for storing usergroups
  52. USER_GROUPS_TABLE_NAME = "usergroups"
  53. // CACHE_TABLE_NAME - caching table
  54. CACHE_TABLE_NAME = "cache"
  55. // HOSTS_TABLE_NAME - the table name for hosts
  56. HOSTS_TABLE_NAME = "hosts"
  57. // == ERROR CONSTS ==
  58. // NO_RECORD - no singular result found
  59. NO_RECORD = "no result found"
  60. // NO_RECORDS - no results found
  61. NO_RECORDS = "could not find any records"
  62. // == DB Constants ==
  63. // INIT_DB - initialize db
  64. INIT_DB = "init"
  65. // CREATE_TABLE - create table const
  66. CREATE_TABLE = "createtable"
  67. // INSERT - insert into db const
  68. INSERT = "insert"
  69. // INSERT_PEER - insert peer into db const
  70. INSERT_PEER = "insertpeer"
  71. // DELETE - delete db record const
  72. DELETE = "delete"
  73. // DELETE_ALL - delete a table const
  74. DELETE_ALL = "deleteall"
  75. // FETCH_ALL - fetch table contents const
  76. FETCH_ALL = "fetchall"
  77. // CLOSE_DB - graceful close of db const
  78. CLOSE_DB = "closedb"
  79. // isconnected
  80. isConnected = "isconnected"
  81. )
  82. var dbMutex sync.RWMutex
  83. func getCurrentDB() map[string]interface{} {
  84. switch servercfg.GetDB() {
  85. case "rqlite":
  86. return RQLITE_FUNCTIONS
  87. case "sqlite":
  88. return SQLITE_FUNCTIONS
  89. case "postgres":
  90. return PG_FUNCTIONS
  91. default:
  92. return SQLITE_FUNCTIONS
  93. }
  94. }
  95. // InitializeDatabase - initializes database
  96. func InitializeDatabase() error {
  97. logger.Log(0, "connecting to", servercfg.GetDB())
  98. tperiod := time.Now().Add(10 * time.Second)
  99. for {
  100. if err := getCurrentDB()[INIT_DB].(func() error)(); err != nil {
  101. logger.Log(0, "unable to connect to db, retrying . . .")
  102. if time.Now().After(tperiod) {
  103. return err
  104. }
  105. } else {
  106. break
  107. }
  108. time.Sleep(2 * time.Second)
  109. }
  110. createTables()
  111. return initializeUUID()
  112. }
  113. func createTables() {
  114. createTable(NETWORKS_TABLE_NAME)
  115. createTable(NODES_TABLE_NAME)
  116. createTable(CERTS_TABLE_NAME)
  117. createTable(DELETED_NODES_TABLE_NAME)
  118. createTable(USERS_TABLE_NAME)
  119. createTable(DNS_TABLE_NAME)
  120. createTable(EXT_CLIENT_TABLE_NAME)
  121. createTable(PEERS_TABLE_NAME)
  122. createTable(SERVERCONF_TABLE_NAME)
  123. createTable(SERVER_UUID_TABLE_NAME)
  124. createTable(GENERATED_TABLE_NAME)
  125. createTable(NODE_ACLS_TABLE_NAME)
  126. createTable(SSO_STATE_CACHE)
  127. createTable(METRICS_TABLE_NAME)
  128. createTable(NETWORK_USER_TABLE_NAME)
  129. createTable(USER_GROUPS_TABLE_NAME)
  130. createTable(CACHE_TABLE_NAME)
  131. createTable(HOSTS_TABLE_NAME)
  132. }
  133. func createTable(tableName string) error {
  134. return getCurrentDB()[CREATE_TABLE].(func(string) error)(tableName)
  135. }
  136. // IsJSONString - checks if valid json
  137. func IsJSONString(value string) bool {
  138. var jsonInt interface{}
  139. var nodeInt models.Node
  140. return json.Unmarshal([]byte(value), &jsonInt) == nil || json.Unmarshal([]byte(value), &nodeInt) == nil
  141. }
  142. // Insert - inserts object into db
  143. func Insert(key string, value string, tableName string) error {
  144. dbMutex.Lock()
  145. defer dbMutex.Unlock()
  146. if key != "" && value != "" && IsJSONString(value) {
  147. return getCurrentDB()[INSERT].(func(string, string, string) error)(key, value, tableName)
  148. } else {
  149. return errors.New("invalid insert " + key + " : " + value)
  150. }
  151. }
  152. // InsertPeer - inserts peer into db
  153. func InsertPeer(key string, value string) error {
  154. dbMutex.Lock()
  155. defer dbMutex.Unlock()
  156. if key != "" && value != "" && IsJSONString(value) {
  157. return getCurrentDB()[INSERT_PEER].(func(string, string) error)(key, value)
  158. } else {
  159. return errors.New("invalid peer insert " + key + " : " + value)
  160. }
  161. }
  162. // DeleteRecord - deletes a record from db
  163. func DeleteRecord(tableName string, key string) error {
  164. dbMutex.Lock()
  165. defer dbMutex.Unlock()
  166. return getCurrentDB()[DELETE].(func(string, string) error)(tableName, key)
  167. }
  168. // DeleteAllRecords - removes a table and remakes
  169. func DeleteAllRecords(tableName string) error {
  170. dbMutex.Lock()
  171. defer dbMutex.Unlock()
  172. err := getCurrentDB()[DELETE_ALL].(func(string) error)(tableName)
  173. if err != nil {
  174. return err
  175. }
  176. err = createTable(tableName)
  177. if err != nil {
  178. return err
  179. }
  180. return nil
  181. }
  182. // FetchRecord - fetches a record
  183. func FetchRecord(tableName string, key string) (string, error) {
  184. results, err := FetchRecords(tableName)
  185. if err != nil {
  186. return "", err
  187. }
  188. if results[key] == "" {
  189. return "", errors.New(NO_RECORD)
  190. }
  191. return results[key], nil
  192. }
  193. // FetchRecords - fetches all records in given table
  194. func FetchRecords(tableName string) (map[string]string, error) {
  195. dbMutex.RLock()
  196. defer dbMutex.RUnlock()
  197. return getCurrentDB()[FETCH_ALL].(func(string) (map[string]string, error))(tableName)
  198. }
  199. // initializeUUID - create a UUID record for server if none exists
  200. func initializeUUID() error {
  201. records, err := FetchRecords(SERVER_UUID_TABLE_NAME)
  202. if err != nil {
  203. if !IsEmptyRecord(err) {
  204. return err
  205. }
  206. } else if len(records) > 0 {
  207. return nil
  208. }
  209. // setup encryption keys
  210. var trafficPubKey, trafficPrivKey, errT = box.GenerateKey(rand.Reader) // generate traffic keys
  211. if errT != nil {
  212. return errT
  213. }
  214. tPriv, err := ncutils.ConvertKeyToBytes(trafficPrivKey)
  215. if err != nil {
  216. return err
  217. }
  218. tPub, err := ncutils.ConvertKeyToBytes(trafficPubKey)
  219. if err != nil {
  220. return err
  221. }
  222. telemetry := models.Telemetry{
  223. UUID: uuid.NewString(),
  224. TrafficKeyPriv: tPriv,
  225. TrafficKeyPub: tPub,
  226. }
  227. telJSON, err := json.Marshal(&telemetry)
  228. if err != nil {
  229. return err
  230. }
  231. return Insert(SERVER_UUID_RECORD_KEY, string(telJSON), SERVER_UUID_TABLE_NAME)
  232. }
  233. // CloseDB - closes a database gracefully
  234. func CloseDB() {
  235. getCurrentDB()[CLOSE_DB].(func())()
  236. }
  237. // IsConnected - tell if the database is connected or not
  238. func IsConnected() bool {
  239. return getCurrentDB()[isConnected].(func() bool)()
  240. }