database.go 7.8 KB

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