2
0

database.go 7.6 KB

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