database.go 8.0 KB

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