database.go 7.4 KB

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