database.go 7.3 KB

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