gosl.go 25 KB

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