gosl.go 25 KB

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