2
0

database.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package database
  2. import (
  3. "crypto/rand"
  4. "encoding/json"
  5. "errors"
  6. "time"
  7. "github.com/google/uuid"
  8. "github.com/gravitl/netmaker/logger"
  9. "github.com/gravitl/netmaker/models"
  10. "github.com/gravitl/netmaker/netclient/ncutils"
  11. "github.com/gravitl/netmaker/servercfg"
  12. "golang.org/x/crypto/nacl/box"
  13. )
  14. // NETWORKS_TABLE_NAME - networks table
  15. const NETWORKS_TABLE_NAME = "networks"
  16. // NODES_TABLE_NAME - nodes table
  17. const NODES_TABLE_NAME = "nodes"
  18. // DELETED_NODES_TABLE_NAME - deleted nodes table
  19. const DELETED_NODES_TABLE_NAME = "deletednodes"
  20. // USERS_TABLE_NAME - users table
  21. const USERS_TABLE_NAME = "users"
  22. // DNS_TABLE_NAME - dns table
  23. const DNS_TABLE_NAME = "dns"
  24. // EXT_CLIENT_TABLE_NAME - ext client table
  25. const EXT_CLIENT_TABLE_NAME = "extclients"
  26. // PEERS_TABLE_NAME - peers table
  27. const PEERS_TABLE_NAME = "peers"
  28. // SERVERCONF_TABLE_NAME - stores server conf
  29. const SERVERCONF_TABLE_NAME = "serverconf"
  30. // SERVER_UUID_TABLE_NAME - stores unique netmaker server data
  31. const SERVER_UUID_TABLE_NAME = "serveruuid"
  32. // SERVER_UUID_RECORD_KEY - telemetry thing
  33. const SERVER_UUID_RECORD_KEY = "serveruuid"
  34. // DATABASE_FILENAME - database file name
  35. const DATABASE_FILENAME = "netmaker.db"
  36. // GENERATED_TABLE_NAME - stores server generated k/v
  37. const GENERATED_TABLE_NAME = "generated"
  38. // NODE_ACLS_TABLE_NAME - stores the node ACL rules
  39. const NODE_ACLS_TABLE_NAME = "nodeacls"
  40. // == ERROR CONSTS ==
  41. // NO_RECORD - no singular result found
  42. const NO_RECORD = "no result found"
  43. // NO_RECORDS - no results found
  44. const NO_RECORDS = "could not find any records"
  45. // == Constants ==
  46. // INIT_DB - initialize db
  47. const INIT_DB = "init"
  48. // CREATE_TABLE - create table const
  49. const CREATE_TABLE = "createtable"
  50. // INSERT - insert into db const
  51. const INSERT = "insert"
  52. // INSERT_PEER - insert peer into db const
  53. const INSERT_PEER = "insertpeer"
  54. // DELETE - delete db record const
  55. const DELETE = "delete"
  56. // DELETE_ALL - delete a table const
  57. const DELETE_ALL = "deleteall"
  58. // FETCH_ALL - fetch table contents const
  59. const FETCH_ALL = "fetchall"
  60. // CLOSE_DB - graceful close of db const
  61. const CLOSE_DB = "closedb"
  62. // MigrationTable - maps function to update database table to new schema
  63. type MigrationTable struct {
  64. Name string
  65. Op UpdateTable
  66. }
  67. //UpdateTable - func to migrate a database table to new schema
  68. type UpdateTable func(string)
  69. // MigrationTables - schema update functions for database tables
  70. // Usage: declare new UpdateTable func and update operation in table
  71. // Example: To add new field to UsersTable (models.User has been updated with NewField)
  72. //func UserTableMigration (table string) {
  73. // var data models.User
  74. // collection, err := FetchRecords(table)
  75. // if err != nil {
  76. // logger.Log(0, "could not update table", table, err.Error())
  77. // return
  78. // }
  79. // for key, value := range collection {
  80. // if err := json.Unmarshal([]byte(value), &data); err != nil {
  81. // logger.Log(0, "failed to unmarshal database table", table, err.Error())
  82. // }
  83. // if data.NewField == "" {
  84. // data.NewFied = defaultvalue
  85. // newRecord, err := json.Marshal(data)
  86. // if err != nil {
  87. // logger.Log(0, "failed to marshal new data for table", table, err.Error())
  88. // continue
  89. // }
  90. // if err := Insert(key, string(newRecord), table); err != nil {
  91. // logger.Log(0, "failed to update", table, ".NewField", err.Error())
  92. // continue
  93. // }
  94. // }
  95. // }
  96. //}
  97. //var Tables []MigrationTable = []MigrationTable{
  98. // ...
  99. // {Name: SERVER_UUID_TABLE_NAME, Op: NilUpdate},
  100. // {Name: USERS_TABLE_NAME, Op: UserTableMigration},
  101. //}
  102. var MigrationTables []MigrationTable = []MigrationTable{
  103. {Name: DELETED_NODES_TABLE_NAME, Op: NilUpdate},
  104. {Name: DNS_TABLE_NAME, Op: NilUpdate},
  105. {Name: EXT_CLIENT_TABLE_NAME, Op: NilUpdate},
  106. {Name: GENERATED_TABLE_NAME, Op: NilUpdate},
  107. {Name: NETWORKS_TABLE_NAME, Op: NilUpdate},
  108. {Name: NODES_TABLE_NAME, Op: NilUpdate},
  109. {Name: NODE_ACLS_TABLE_NAME, Op: NilUpdate},
  110. {Name: PEERS_TABLE_NAME, Op: NilUpdate},
  111. {Name: SERVERCONF_TABLE_NAME, Op: NilUpdate},
  112. {Name: SERVER_UUID_TABLE_NAME, Op: NilUpdate},
  113. {Name: USERS_TABLE_NAME, Op: NilUpdate},
  114. }
  115. // NilUpdate - function to be called when table schema is not being updated
  116. func NilUpdate(string) {
  117. return
  118. }
  119. func getCurrentDB() map[string]interface{} {
  120. switch servercfg.GetDB() {
  121. case "rqlite":
  122. return RQLITE_FUNCTIONS
  123. case "sqlite":
  124. return SQLITE_FUNCTIONS
  125. case "postgres":
  126. return PG_FUNCTIONS
  127. default:
  128. return SQLITE_FUNCTIONS
  129. }
  130. }
  131. // InitializeDatabase - initializes database
  132. func InitializeDatabase() error {
  133. logger.Log(0, "connecting to", servercfg.GetDB())
  134. tperiod := time.Now().Add(10 * time.Second)
  135. for {
  136. if err := getCurrentDB()[INIT_DB].(func() error)(); err != nil {
  137. logger.Log(0, "unable to connect to db, retrying . . .")
  138. if time.Now().After(tperiod) {
  139. return err
  140. }
  141. } else {
  142. break
  143. }
  144. time.Sleep(2 * time.Second)
  145. }
  146. createTables()
  147. return initializeUUID()
  148. }
  149. func createTables() {
  150. createTable(NETWORKS_TABLE_NAME)
  151. createTable(NODES_TABLE_NAME)
  152. createTable(DELETED_NODES_TABLE_NAME)
  153. createTable(USERS_TABLE_NAME)
  154. createTable(DNS_TABLE_NAME)
  155. createTable(EXT_CLIENT_TABLE_NAME)
  156. createTable(PEERS_TABLE_NAME)
  157. createTable(SERVERCONF_TABLE_NAME)
  158. createTable(SERVER_UUID_TABLE_NAME)
  159. createTable(GENERATED_TABLE_NAME)
  160. createTable(NODE_ACLS_TABLE_NAME)
  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. if key != "" && value != "" && IsJSONString(value) {
  174. return getCurrentDB()[INSERT].(func(string, string, string) error)(key, value, tableName)
  175. } else {
  176. return errors.New("invalid insert " + key + " : " + value)
  177. }
  178. }
  179. // InsertPeer - inserts peer into db
  180. func InsertPeer(key string, value string) error {
  181. if key != "" && value != "" && IsJSONString(value) {
  182. return getCurrentDB()[INSERT_PEER].(func(string, string) error)(key, value)
  183. } else {
  184. return errors.New("invalid peer insert " + key + " : " + value)
  185. }
  186. }
  187. // DeleteRecord - deletes a record from db
  188. func DeleteRecord(tableName string, key string) error {
  189. return getCurrentDB()[DELETE].(func(string, string) error)(tableName, key)
  190. }
  191. // DeleteAllRecords - removes a table and remakes
  192. func DeleteAllRecords(tableName string) error {
  193. err := getCurrentDB()[DELETE_ALL].(func(string) error)(tableName)
  194. if err != nil {
  195. return err
  196. }
  197. err = createTable(tableName)
  198. if err != nil {
  199. return err
  200. }
  201. return nil
  202. }
  203. // FetchRecord - fetches a record
  204. func FetchRecord(tableName string, key string) (string, error) {
  205. results, err := FetchRecords(tableName)
  206. if err != nil {
  207. return "", err
  208. }
  209. if results[key] == "" {
  210. return "", errors.New(NO_RECORD)
  211. }
  212. return results[key], nil
  213. }
  214. // FetchRecords - fetches all records in given table
  215. func FetchRecords(tableName string) (map[string]string, error) {
  216. return getCurrentDB()[FETCH_ALL].(func(string) (map[string]string, error))(tableName)
  217. }
  218. // initializeUUID - create a UUID record for server if none exists
  219. func initializeUUID() error {
  220. records, err := FetchRecords(SERVER_UUID_TABLE_NAME)
  221. if err != nil {
  222. if !IsEmptyRecord(err) {
  223. return err
  224. }
  225. } else if len(records) > 0 {
  226. return nil
  227. }
  228. // setup encryption keys
  229. var trafficPubKey, trafficPrivKey, errT = box.GenerateKey(rand.Reader) // generate traffic keys
  230. if errT != nil {
  231. return errT
  232. }
  233. tPriv, err := ncutils.ConvertKeyToBytes(trafficPrivKey)
  234. if err != nil {
  235. return err
  236. }
  237. tPub, err := ncutils.ConvertKeyToBytes(trafficPubKey)
  238. if err != nil {
  239. return err
  240. }
  241. telemetry := models.Telemetry{
  242. UUID: uuid.NewString(),
  243. TrafficKeyPriv: tPriv,
  244. TrafficKeyPub: tPub,
  245. }
  246. telJSON, err := json.Marshal(&telemetry)
  247. if err != nil {
  248. return err
  249. }
  250. return Insert(SERVER_UUID_RECORD_KEY, string(telJSON), SERVER_UUID_TABLE_NAME)
  251. }
  252. // CloseDB - closes a database gracefully
  253. func CloseDB() {
  254. getCurrentDB()[CLOSE_DB].(func())()
  255. }