database.go 7.9 KB

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