1
0

gosl.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. // gosl is a basic example of how to develop external web services for Second Life/OpenSimulator using the Go programming language.
  2. package main
  3. import (
  4. "bufio"
  5. "compress/bzip2"
  6. "encoding/csv"
  7. "encoding/json"
  8. "flag"
  9. "fmt"
  10. "github.com/dgraph-io/badger"
  11. "github.com/dgraph-io/badger/options"
  12. "github.com/fsnotify/fsnotify"
  13. "github.com/op/go-logging"
  14. "github.com/spf13/viper"
  15. "github.com/tidwall/buntdb"
  16. "gopkg.in/natefinch/lumberjack.v2"
  17. "io"
  18. "net/http"
  19. "net/http/fcgi"
  20. "os"
  21. "path/filepath"
  22. "regexp"
  23. "runtime"
  24. "strings"
  25. "time"
  26. )
  27. const NullUUID = "00000000-0000-0000-0000-000000000000" // always useful when we deal with SL/OpenSimulator...
  28. const databaseName = "gosl-database.db" // for BuntDB
  29. // Logging setup.
  30. var log = logging.MustGetLogger("gosl") // configuration for the go-logging logger, must be available everywhere
  31. var logFormat logging.Formatter
  32. // Opt is used for Badger database setup.
  33. var Opt badger.Options
  34. // AvatarUUID is the type that we store in the database; we keep a record from which grid it came from.
  35. type avatarUUID struct {
  36. UUID string // needs to be capitalised for JSON marshalling (it has to do with the way it works)
  37. Grid string
  38. }
  39. /*
  40. .__
  41. _____ _____ |__| ____
  42. / \\__ \ | |/ \
  43. | Y Y \/ __ \| | | \
  44. |__|_| (____ /__|___| /
  45. \/ \/ \/
  46. */
  47. // Configuration options
  48. type goslConfigOptions struct {
  49. BATCH_BLOCK *int // how many entries to write to the database as a block; the bigger, the faster, but the more memory it consumes
  50. noMemory, isServer, isShell *bool
  51. myDir, myPort, importFilename, database *string
  52. dbNamePath string // for BuntDB
  53. logFilename string // for logs
  54. maxSize, maxBackups, maxAge int // logs configuration option
  55. }
  56. var goslConfig goslConfigOptions
  57. // loadConfiguration reads our configuration from a config.toml file
  58. func loadConfiguration() {
  59. fmt.Print("Reading gosl-basic configuration:") // note that we might not have go-logging active as yet, so we use fmt
  60. // Open our config file and extract relevant data from there
  61. err := viper.ReadInConfig() // Find and read the config file
  62. if err != nil {
  63. fmt.Println("Error reading config file:", err)
  64. return // we might still get away with this!
  65. }
  66. viper.SetDefault("config.BATCH_BLOCK", 100000) // NOTE(gwyneth): the authors of say that 100000 is way too much for Badger // NOTE(gwyneth): let's see what happens with BuntDB
  67. *goslConfig.BATCH_BLOCK = viper.GetInt("config.BATCH_BLOCK")
  68. viper.SetDefault("config.myPort", 3000)
  69. *goslConfig.myPort = viper.GetString("config.myPort")
  70. viper.SetDefault("config.myDir", "slkvdb")
  71. *goslConfig.myDir = viper.GetString("config.myDir")
  72. viper.SetDefault("config.isServer", false)
  73. *goslConfig.isServer = viper.GetBool("config.isServer")
  74. viper.SetDefault("config.isShell", false)
  75. *goslConfig.isShell = viper.GetBool("config.isShell")
  76. viper.SetDefault("config.database", "badger")
  77. *goslConfig.database = viper.GetString("config.database")
  78. viper.SetDefault("config.importFilename", "name2key.csv.bz2")
  79. *goslConfig.importFilename = viper.GetString("config.importFilename")
  80. viper.SetDefault("config.noMemory", false)
  81. *goslConfig.noMemory = viper.GetBool("config.noMemory")
  82. // Logging options
  83. viper.SetDefault("config.logFilename", "gosl.log")
  84. goslConfig.logFilename = viper.GetString("config.logFilename")
  85. viper.SetDefault("config.maxSize", 10)
  86. goslConfig.maxSize = viper.GetInt("config.maxSize")
  87. viper.SetDefault("config.maxBackups", 3)
  88. goslConfig.maxBackups = viper.GetInt("config.maxBackups")
  89. viper.SetDefault("config.maxAge", 28)
  90. goslConfig.maxAge = viper.GetInt("config.maxAge")
  91. }
  92. // main() starts here.
  93. func main() {
  94. loadConfiguration()
  95. // Flag setup; it overrides (hopefully) what is in the configuration file
  96. goslConfig.myPort = flag.String("port", "3000", "Server port")
  97. goslConfig.myDir = flag.String("dir", "slkvdb", "Directory where database files are stored")
  98. goslConfig.isServer = flag.Bool("server", false, "Run as server on port " + *goslConfig.myPort)
  99. goslConfig.isShell = flag.Bool("shell", false, "Run as an interactive shell")
  100. goslConfig.importFilename = flag.String("import", "name2key.csv.bz2", "Import database from W-Hat (use the csv.bz2 version)")
  101. goslConfig.database = flag.String("database", "badger", "Database type (currently BuntDB or Badger)")
  102. goslConfig.noMemory = flag.Bool("nomemory", false, "Attempt to use only disk to save memory on Badger (important for shared webservers)")
  103. // this will allow our configuration file to be 'read on demand'
  104. viper.WatchConfig()
  105. viper.OnConfigChange(func(e fsnotify.Event) {
  106. if *goslConfig.isServer || *goslConfig.isShell {
  107. fmt.Println("Config file changed:", e.Name) // BUG(gwyneth): FastCGI cannot write to output
  108. }
  109. loadConfiguration()
  110. })
  111. // default is FastCGI
  112. flag.Parse()
  113. // NOTE(gwyneth): We cannot write to stdout if we're running as FastCGI, only to logs!
  114. if *goslConfig.isServer || *goslConfig.isShell {
  115. fmt.Println("gosl is starting...")
  116. }
  117. // Setup the lumberjack rotating logger. This is because we need it for the go-logging logger when writing to files. (20170813)
  118. rotatingLogger := &lumberjack.Logger{
  119. Filename: goslConfig.logFilename,
  120. MaxSize: goslConfig.maxSize, // megabytes
  121. MaxBackups: goslConfig.maxBackups,
  122. MaxAge: goslConfig.maxAge, //days
  123. }
  124. // Set formatting for stderr and file (basically the same).
  125. logFormat := logging.MustStringFormatter(`%{color}%{time:2006/01/02 15:04:05.0} %{shortfile} - %{shortfunc} ▶ %{level:.4s}%{color:reset} %{message}`) // must be initialised or all hell breaks loose
  126. // Setup the go-logging Logger. Do **not** log to stderr if running as FastCGI!
  127. backendFile := logging.NewLogBackend(rotatingLogger, "", 0)
  128. backendFileFormatter := logging.NewBackendFormatter(backendFile, logFormat)
  129. backendFileLeveled := logging.AddModuleLevel(backendFileFormatter)
  130. backendFileLeveled.SetLevel(logging.INFO, "gosl") // we just send debug data to logs if we run as shell
  131. if *goslConfig.isServer || *goslConfig.isShell {
  132. backendStderr := logging.NewLogBackend(os.Stderr, "", 0)
  133. backendStderrFormatter := logging.NewBackendFormatter(backendStderr, logFormat)
  134. backendStderrLeveled := logging.AddModuleLevel(backendStderrFormatter)
  135. if *goslConfig.isShell {
  136. backendStderrLeveled.SetLevel(logging.DEBUG, "gosl") // shell is meant to be for debugging mostly
  137. } else {
  138. backendStderrLeveled.SetLevel(logging.INFO, "gosl")
  139. }
  140. logging.SetBackend(backendStderrLeveled, backendFileLeveled)
  141. } else {
  142. logging.SetBackend(backendFileLeveled) // FastCGI only logs to file
  143. }
  144. // Check if this directory actually exists; if not, create it. Panic if something wrong happens (we cannot proceed without a valid directory for the database to be written
  145. if stat, err := os.Stat(*goslConfig.myDir); err == nil && stat.IsDir() {
  146. // path is a valid directory
  147. log.Infof("Valid directory: %s\n", *goslConfig.myDir)
  148. } else {
  149. // try to create directory
  150. err = os.Mkdir(*goslConfig.myDir, 0700)
  151. checkErrPanic(err) // cannot make directory, panic and exit logging what went wrong
  152. log.Debugf("Created new directory: %s\n", *goslConfig.myDir)
  153. }
  154. if *goslConfig.database == "badger" {
  155. Opt = badger.DefaultOptions
  156. Opt.Dir = *goslConfig.myDir
  157. Opt.ValueDir = Opt.Dir
  158. Opt.TableLoadingMode = options.MemoryMap
  159. //Opt.TableLoadingMode = options.FileIO
  160. }
  161. if *goslConfig.noMemory && *goslConfig.database == "badger" {
  162. // Opt.TableLoadingMode = options.FileIO // use standard file I/O operations for tables instead of LoadRAM
  163. // Opt.TableLoadingMode = options.MemoryMap // MemoryMap indicates that that the file must be memory-mapped - https://github.com/dgraph-io/badger/issues/224#issuecomment-329643771
  164. Opt.TableLoadingMode = options.FileIO
  165. // Opt.ValueLogFileSize = 1048576
  166. Opt.MaxTableSize = 1048576 * 12
  167. Opt.NumMemtables = 0
  168. Opt.MaxLevels = 10
  169. Opt.SyncWrites = false
  170. Opt.NumCompactors = 10
  171. Opt.NumLevelZeroTables = 10
  172. // Opt.maxBatchSize =
  173. // Opt.maxBatchCount =
  174. *goslConfig.BATCH_BLOCK = 10000 // try to import less at each time, it will take longer but hopefully work
  175. log.Info("Trying to avoid too much memory consumption")
  176. }
  177. // Do some testing to see if the database is available
  178. const testAvatarName = "Nobody Here"
  179. var err error
  180. log.Info("gosl started and logging is set up. Proceeding to test KV database.")
  181. var testValue = avatarUUID{ NullUUID, "all grids" }
  182. jsonTestValue, err := json.Marshal(testValue)
  183. checkErrPanic(err) // something went VERY wrong
  184. if *goslConfig.database == "badger" {
  185. kv, err := badger.Open(Opt)
  186. checkErrPanic(err) // should probably panic, cannot prep new database
  187. txn := kv.NewTransaction(true)
  188. err = txn.Set([]byte(testAvatarName), jsonTestValue, 0x00)
  189. checkErrPanic(err)
  190. err = txn.Commit(nil)
  191. checkErrPanic(err)
  192. log.Debugf("SET %+v (json: %v)\n", testValue, string(jsonTestValue))
  193. kv.Close()
  194. } else {
  195. /* NOTE(gwyneth): this fails because pointers to strings do not implement len(). Duh!
  196. if *goslConfig.myDir[len(*goslConfig.myDir)-1] != os.PathSeparator {
  197. *goslConfig.myDir = append(*goslConfig.myDir + os.PathSeparator
  198. } */
  199. goslConfig.dbNamePath = *goslConfig.myDir + string(os.PathSeparator) + databaseName
  200. db, err := buntdb.Open(goslConfig.dbNamePath)
  201. checkErrPanic(err)
  202. err = db.Update(func(tx *buntdb.Tx) error {
  203. _, _, err := tx.Set(testAvatarName, string(jsonTestValue), nil)
  204. return err
  205. })
  206. checkErr(err)
  207. log.Debugf("SET %+v (json: %v)\n", testValue, string(jsonTestValue))
  208. db.Close()
  209. }
  210. // common to both databases:
  211. key, grid := searchKVname(testAvatarName)
  212. log.Debugf("GET '%s' returned '%s' [grid '%s']\n", testAvatarName, key, grid)
  213. log.Info("KV database seems fine.")
  214. if *goslConfig.importFilename != "" {
  215. log.Info("Attempting to import", *goslConfig.importFilename, "...")
  216. importDatabase(*goslConfig.importFilename)
  217. log.Info("Database finished import.")
  218. }
  219. if *goslConfig.isShell {
  220. log.Info("Starting to run as interactive shell")
  221. reader := bufio.NewReader(os.Stdin)
  222. fmt.Println("Ctrl-C to quit.")
  223. var err error // to avoid assigning text in a different scope (this is a bit awkward, but that's the problem with bi-assignment)
  224. var checkInput, avatarName, avatarKey, gridName string
  225. for {
  226. // Prompt and read
  227. fmt.Print("Enter avatar name or UUID: ")
  228. checkInput, err = reader.ReadString('\n')
  229. checkErr(err)
  230. checkInput = strings.TrimRight(checkInput, "\r\n")
  231. // fmt.Printf("Ok, got %s length is %d and UUID is %v\n", checkInput, len(checkInput), isValidUUID(checkInput))
  232. if (len(checkInput) == 36) && isValidUUID(checkInput) {
  233. avatarName, gridName = searchKVUUID(checkInput)
  234. avatarKey = checkInput
  235. } else {
  236. avatarKey, gridName = searchKVname(checkInput)
  237. avatarName = checkInput
  238. }
  239. if avatarName != NullUUID && avatarKey != NullUUID {
  240. fmt.Println(avatarName, "which has UUID:", avatarKey, "comes from grid:", gridName)
  241. } else {
  242. fmt.Println("Sorry, unknown input", checkInput)
  243. }
  244. }
  245. // never leaves until Ctrl-C
  246. }
  247. // set up routing.
  248. // NOTE(gwyneth): one function only because FastCGI seems to have problems with multiple handlers.
  249. http.HandleFunc("/", handler)
  250. log.Info("Directory for database:", *goslConfig.myDir)
  251. if (*goslConfig.isServer) {
  252. log.Info("Starting to run as web server on port " + *goslConfig.myPort)
  253. err := http.ListenAndServe(":" + *goslConfig.myPort, nil) // set listen port
  254. checkErrPanic(err) // if it can't listen to all the above, then it has to abort anyway
  255. } else {
  256. // default is to run as FastCGI!
  257. // works like a charm thanks to http://www.dav-muz.net/blog/2013/09/how-to-use-go-and-fastcgi/
  258. log.Debug("http.DefaultServeMux is", http.DefaultServeMux)
  259. if err := fcgi.Serve(nil, nil); err != nil {
  260. checkErrPanic(err)
  261. }
  262. }
  263. // we should never have reached this point!
  264. log.Error("Unknown usage! This application may run as a standalone server, as FastCGI application, or as an interactive shell")
  265. if *goslConfig.isServer || *goslConfig.isShell {
  266. flag.PrintDefaults()
  267. }
  268. }
  269. // handler deals with incoming queries and/or associates avatar names with keys depending on parameters.
  270. // Basically we check if both an avatar name and a UUID key has been received: if yes, this means a new entry;
  271. // if just the avatar name was received, it means looking up its key;
  272. // if just the key was received, it means looking up the name (not necessary since llKey2Name does that, but it's just to illustrate);
  273. // if nothing is received, then return an error
  274. func handler(w http.ResponseWriter, r *http.Request) {
  275. if err := r.ParseForm(); err != nil {
  276. logErrHTTP(w, http.StatusNotFound, "No avatar and/or UUID received")
  277. return
  278. }
  279. // test first if this comes from Second Life or OpenSimulator
  280. /*
  281. if r.Header.Get("X-Secondlife-Region") == "" {
  282. logErrHTTP(w, http.StatusForbidden, "Sorry, this application only works inside Second Life.")
  283. return
  284. }
  285. */
  286. name := r.Form.Get("name") // can be empty
  287. key := r.Form.Get("key") // can be empty
  288. compat := r.Form.Get("compat") // compatibility mode with W-Hat
  289. var valueToInsert avatarUUID
  290. messageToSL := "" // this is what we send back to SL - defined here due to scope issues.
  291. if name != "" {
  292. if key != "" {
  293. // we received both: add a new entry
  294. valueToInsert.UUID = key
  295. valueToInsert.Grid = r.Header.Get("X-Secondlife-Shard")
  296. jsonValueToInsert, err := json.Marshal(valueToInsert)
  297. checkErr(err)
  298. if *goslConfig.database == "badger" {
  299. kv, err := badger.Open(Opt)
  300. checkErrPanic(err) // should probably panic
  301. txn := kv.NewTransaction(true)
  302. defer txn.Discard()
  303. err = txn.Set([]byte(name), jsonValueToInsert, 0x00)
  304. checkErrPanic(err)
  305. err = txn.Commit(nil)
  306. checkErrPanic(err)
  307. kv.Close()
  308. } else {
  309. db, err := buntdb.Open(goslConfig.dbNamePath)
  310. checkErrPanic(err)
  311. defer db.Close()
  312. err = db.Update(func(tx *buntdb.Tx) error {
  313. _, _, err := tx.Set(name, string(jsonValueToInsert), nil)
  314. return err
  315. })
  316. checkErr(err)
  317. }
  318. messageToSL += "Added new entry for '" + name + "' which is: " + valueToInsert.UUID + " from grid: '" + valueToInsert.Grid + "'"
  319. } else {
  320. // we received a name: look up its UUID key and grid.
  321. key, grid := searchKVname(name)
  322. if compat == "false" {
  323. messageToSL += "UUID for '" + name + "' is: " + key + " from grid: '" + grid + "'"
  324. } else { // empty also means true!
  325. messageToSL += key
  326. }
  327. }
  328. } else if key != "" {
  329. // in this scenario, we have the UUID key but no avatar name: do the equivalent of a llKey2Name (slow)
  330. name, grid := searchKVUUID(key)
  331. if compat == "false" {
  332. messageToSL += "Avatar name for " + key + "' is '" + name + "' on grid: '" + grid + "'"
  333. } else { // empty also means true!
  334. messageToSL += name
  335. }
  336. } else {
  337. // neither UUID key nor avatar received, this is an error
  338. logErrHTTP(w, http.StatusNotFound, "Empty avatar name and UUID key received, cannot proceed")
  339. return
  340. }
  341. w.WriteHeader(http.StatusOK)
  342. w.Header().Set("Content-type", "text/plain; charset=utf-8")
  343. fmt.Fprintf(w, messageToSL)
  344. }
  345. // searchKVname searches the KV database for an avatar name.
  346. func searchKVname(avatarName string) (UUID string, grid string) {
  347. var val = avatarUUID{ NullUUID, "" }
  348. time_start := time.Now()
  349. var err error // to deal with scope issues
  350. if *goslConfig.database == "badger" {
  351. kv, err := badger.Open(Opt)
  352. checkErrPanic(err)
  353. defer kv.Close()
  354. err = kv.View(func(txn *badger.Txn) error {
  355. item, err := txn.Get([]byte(avatarName))
  356. if err != nil {
  357. return err
  358. }
  359. data, err := item.Value()
  360. if err != nil {
  361. log.Errorf("Error '%s' while getting data from %v\n", err, item)
  362. return err
  363. }
  364. err = json.Unmarshal(data, &val)
  365. if err != nil {
  366. log.Errorf("Error while unparsing UUID for name: '%s' (%v)\n", avatarName, err)
  367. return err
  368. }
  369. return nil
  370. })
  371. } else {
  372. db, err := buntdb.Open(goslConfig.dbNamePath)
  373. checkErrPanic(err)
  374. defer db.Close()
  375. var data string
  376. err = db.View(func(tx *buntdb.Tx) error {
  377. data, err = tx.Get(avatarName)
  378. return err
  379. })
  380. err = json.Unmarshal([]byte(data), &val)
  381. if err != nil {
  382. log.Errorf("Error while unparsing UUID for name: '%s' (%v)\n", avatarName, err)
  383. }
  384. }
  385. time_end := time.Now()
  386. diffTime := time_end.Sub(time_start)
  387. log.Debugf("Time to lookup '%s': %v\n", avatarName, diffTime)
  388. if err != nil {
  389. return NullUUID, ""
  390. } // else:
  391. return val.UUID, val.Grid
  392. }
  393. // searchKVUUID searches the KV database for an avatar key.
  394. func searchKVUUID(avatarKey string) (name string, grid string) {
  395. time_start := time.Now()
  396. checks := 0
  397. var val = avatarUUID{ NullUUID, "" }
  398. var found string
  399. if *goslConfig.database == "badger" {
  400. kv, err := badger.Open(Opt)
  401. checkErr(err) // should probably panic
  402. itOpt := badger.DefaultIteratorOptions
  403. if !*goslConfig.noMemory {
  404. itOpt.PrefetchValues = true
  405. itOpt.PrefetchSize = 1000 // attempt to get this a little bit more efficient; we have many small entries, so this is not too much
  406. } else {
  407. itOpt.PrefetchValues = false
  408. }
  409. txn := kv.NewTransaction(true)
  410. defer txn.Discard()
  411. err = kv.View(func(txn *badger.Txn) error {
  412. itr := txn.NewIterator(itOpt)
  413. defer itr.Close()
  414. for itr.Rewind(); itr.Valid(); itr.Next() {
  415. item := itr.Item()
  416. data, err := item.Value()
  417. if err != nil {
  418. log.Errorf("Error '%s' while getting data from %v\n", err, item)
  419. return err
  420. }
  421. err = json.Unmarshal(data, &val)
  422. if err != nil {
  423. log.Errorf("Error '%s' while unparsing UUID for data: %v\n", err, data)
  424. return err
  425. }
  426. checks++ //Just to see how many checks we made, for statistical purposes
  427. if avatarKey == val.UUID {
  428. found = string(item.Key())
  429. break
  430. }
  431. }
  432. return nil
  433. })
  434. kv.Close()
  435. } else {
  436. db, err := buntdb.Open(goslConfig.dbNamePath)
  437. checkErrPanic(err)
  438. err = db.View(func(tx *buntdb.Tx) error {
  439. err := tx.Ascend("", func(key, value string) bool {
  440. err = json.Unmarshal([]byte(value), &val)
  441. if err != nil {
  442. log.Errorf("Error '%s' while unparsing UUID for value: %v\n", err, value)
  443. }
  444. checks++ //Just to see how many checks we made, for statistical purposes
  445. if avatarKey == val.UUID {
  446. found = key
  447. return false
  448. }
  449. return true
  450. })
  451. return err
  452. })
  453. db.Close()
  454. }
  455. time_end := time.Now()
  456. diffTime := time_end.Sub(time_start)
  457. log.Debugf("Made %d checks for '%s' in %v\n", checks, avatarKey, diffTime)
  458. return found, val.Grid
  459. }
  460. // importDatabase is essentially reading a bzip2'ed CSV file with UUID,AvatarName downloaded from http://w-hat.com/#name2key .
  461. // One could theoretically set a cron job to get this file, save it on disk periodically, and keep the database up-to-date
  462. // see https://stackoverflow.com/questions/24673335/how-do-i-read-a-gzipped-csv-file for the actual usage of these complicated things!
  463. func importDatabase(filename string) {
  464. filehandler, err := os.Open(filename)
  465. if err != nil {
  466. log.Fatal(err)
  467. }
  468. defer filehandler.Close()
  469. gr := bzip2.NewReader(filehandler) // open bzip2 reader
  470. cr := csv.NewReader(gr) // open csv reader and feed the bzip2 reader into it
  471. limit := 0 // outside of for loop so that we can count how many entries we had in total
  472. time_start := time.Now() // we want to get an idea on how long this takes
  473. if *goslConfig.database == "badger" {
  474. // prepare connection to KV database
  475. kv, err := badger.Open(Opt)
  476. checkErrPanic(err) // should probably panic
  477. defer kv.Close()
  478. txn := kv.NewTransaction(true) // start new transaction; we will commit only every BATCH_BLOCK entries
  479. defer txn.Discard()
  480. for ;;limit++ {
  481. record, err := cr.Read()
  482. if err == io.EOF {
  483. break
  484. } else if err != nil {
  485. log.Fatal(err)
  486. }
  487. jsonNewEntry, err := json.Marshal(avatarUUID{ record[0], "Production" }) // W-Hat keys come all from the main LL grid, known as 'Production'
  488. if err != nil {
  489. log.Warning(err)
  490. } else {
  491. err = txn.Set([]byte(record[1]), jsonNewEntry, 0x00)
  492. if err != nil {
  493. log.Fatal(err)
  494. }
  495. }
  496. if limit % *goslConfig.BATCH_BLOCK == 0 && limit != 0 { // we do not run on the first time, and then only every BATCH_BLOCK times
  497. log.Info("Processing:", limit)
  498. err = txn.Commit(nil)
  499. if err != nil {
  500. log.Fatal(err)
  501. }
  502. runtime.GC()
  503. txn = kv.NewTransaction(true) // start a new transaction
  504. defer txn.Discard()
  505. }
  506. }
  507. // commit last batch
  508. err = txn.Commit(nil)
  509. if err != nil {
  510. log.Fatal(err)
  511. }
  512. kv.PurgeOlderVersions()
  513. } else {
  514. db, err := buntdb.Open(goslConfig.dbNamePath)
  515. checkErrPanic(err)
  516. defer db.Close()
  517. txn, err := db.Begin(true)
  518. checkErrPanic(err)
  519. //defer txn.Commit()
  520. // very similar to Badger code...
  521. for ;;limit++ {
  522. record, err := cr.Read()
  523. if err == io.EOF {
  524. break
  525. } else if err != nil {
  526. log.Fatal(err)
  527. }
  528. jsonNewEntry, err := json.Marshal(avatarUUID{ record[0], "Production" }) // W-Hat keys come all from the main LL grid, known as 'Production'
  529. if err != nil {
  530. log.Warning(err)
  531. } else {
  532. _, _, err = txn.Set(record[1], string(jsonNewEntry), nil)
  533. if err != nil {
  534. log.Fatal(err)
  535. }
  536. }
  537. if limit % *goslConfig.BATCH_BLOCK == 0 && limit != 0 { // we do not run on the first time, and then only every BATCH_BLOCK times
  538. log.Info("Processing:", limit)
  539. err = txn.Commit()
  540. if err != nil {
  541. log.Fatal(err)
  542. }
  543. runtime.GC()
  544. txn, err = db.Begin(true) // start a new transaction
  545. checkErrPanic(err)
  546. //defer txn.Commit()
  547. }
  548. }
  549. // commit last batch
  550. err = txn.Commit()
  551. if err != nil {
  552. log.Fatal(err)
  553. }
  554. db.Shrink()
  555. }
  556. time_end := time.Now()
  557. diffTime := time_end.Sub(time_start)
  558. log.Info("Total read", limit, "records (or thereabouts) in", diffTime)
  559. }
  560. // NOTE(gwyneth):Auxiliary functions which I'm always using...
  561. // checkErrPanic logs a fatal error and panics.
  562. func checkErrPanic(err error) {
  563. if err != nil {
  564. pc, file, line, ok := runtime.Caller(1)
  565. log.Panic(filepath.Base(file), ":", line, ":", pc, ok, " - panic:", err)
  566. }
  567. }
  568. // checkErr checks if there is an error, and if yes, it logs it out and continues.
  569. // this is for 'normal' situations when we want to get a log if something goes wrong but do not need to panic
  570. func checkErr(err error) {
  571. if err != nil {
  572. pc, file, line, ok := runtime.Caller(1)
  573. log.Error(filepath.Base(file), ":", line, ":", pc, ok, " - error:", err)
  574. }
  575. }
  576. // Auxiliary functions for HTTP handling
  577. // checkErrHTTP returns an error via HTTP and also logs the error.
  578. func checkErrHTTP(w http.ResponseWriter, httpStatus int, errorMessage string, err error) {
  579. if err != nil {
  580. http.Error(w, fmt.Sprintf(errorMessage, err), httpStatus)
  581. pc, file, line, ok := runtime.Caller(1)
  582. log.Error("(", http.StatusText(httpStatus), ") ", filepath.Base(file), ":", line, ":", pc, ok, " - error:", errorMessage, err)
  583. }
  584. }
  585. // checkErrPanicHTTP returns an error via HTTP and logs the error with a panic.
  586. func checkErrPanicHTTP(w http.ResponseWriter, httpStatus int, errorMessage string, err error) {
  587. if err != nil {
  588. http.Error(w, fmt.Sprintf(errorMessage, err), httpStatus)
  589. pc, file, line, ok := runtime.Caller(1)
  590. log.Panic("(", http.StatusText(httpStatus), ") ", filepath.Base(file), ":", line, ":", pc, ok, " - panic:", errorMessage, err)
  591. }
  592. }
  593. // logErrHTTP assumes that the error message was already composed and writes it to HTTP and logs it.
  594. // this is mostly to avoid code duplication and make sure that all entries are written similarly
  595. func logErrHTTP(w http.ResponseWriter, httpStatus int, errorMessage string) {
  596. http.Error(w, errorMessage, httpStatus)
  597. log.Error("(" + http.StatusText(httpStatus) + ") " + errorMessage)
  598. }
  599. // funcName is @Sonia's solution to get the name of the function that Go is currently running.
  600. // This will be extensively used to deal with figuring out where in the code the errors are!
  601. // Source: https://stackoverflow.com/a/10743805/1035977 (20170708)
  602. func funcName() string {
  603. pc, _, _, _ := runtime.Caller(1)
  604. return runtime.FuncForPC(pc).Name()
  605. }
  606. // isValidUUID checks if the UUID is valid.
  607. // Thanks to Patrick D'Appollonio https://stackoverflow.com/questions/25051675/how-to-validate-uuid-v4-in-go
  608. func isValidUUID(uuid string) bool {
  609. r := regexp.MustCompile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$")
  610. return r.MatchString(uuid)
  611. }