database.go 7.9 KB

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