1
0

gosl.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. // gosl implements the name2key/key2name functionality for about
  2. // ten million avatar names (≈⅙ of the total database).
  3. package main
  4. import (
  5. // "bufio" // replaced by the more sophisticated readline (gwyneth 20211106)
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "net/http/fcgi"
  10. "os"
  11. "path/filepath"
  12. // "regexp"
  13. "strings"
  14. // "time"
  15. "github.com/dgraph-io/badger/v3"
  16. // "github.com/dgraph-io/badger/options"
  17. // "github.com/fsnotify/fsnotify"
  18. "github.com/google/uuid"
  19. "github.com/op/go-logging"
  20. flag "github.com/spf13/pflag"
  21. "github.com/spf13/viper"
  22. "github.com/syndtr/goleveldb/leveldb"
  23. "github.com/tidwall/buntdb"
  24. "gitlab.com/cznic/readline"
  25. // "gopkg.in/go-playground/validator.v9" // to validate UUIDs... and a lot of thinks
  26. "gopkg.in/natefinch/lumberjack.v2"
  27. )
  28. const NullUUID = "00000000-0000-0000-0000-000000000000" // always useful when we deal with SL/OpenSimulator...
  29. const databaseName = "gosl-database.db" // for BuntDB
  30. // Logging setup.
  31. var log = logging.MustGetLogger("gosl") // configuration for the go-logging logger, must be available everywhere
  32. var logFormat logging.Formatter
  33. // Opt is used for Badger database setup.
  34. var Opt badger.Options
  35. // AvatarUUID is the type that we store in the database; we keep a record from which grid it came from.
  36. // Field names need to be capitalised for JSON marshalling (it has to do with the way it works)
  37. // Note that we will store both UUID -> AvatarName *and* AvatarName -> UUID on the same database,
  38. //
  39. // thus the apparent redundancy in fields! (gwyneth 20211030)
  40. //
  41. // The 'validate' decorator is for usage with the go-playground validator, currently unused (gwyneth 20211031)
  42. type avatarUUID struct {
  43. AvatarName string `json:"name" form:"name" binding:"required" validate:"omitempty,alphanum"`
  44. UUID string `json:"key" form:"key" binding:"required" validate:"omitempty,uuid4_rfc4122"`
  45. Grid string `json:"grid" form:"grid" validate:"omitempty,alphanum"`
  46. }
  47. /*
  48. .__
  49. _____ _____ |__| ____
  50. / \\__ \ | |/ \
  51. | Y Y \/ __ \| | | \
  52. |__|_| (____ /__|___| /
  53. \/ \/ \/
  54. */
  55. // Configuration options.
  56. type goslConfigOptions struct {
  57. BATCH_BLOCK int // how many entries to write to the database as a block; the bigger, the faster, but the more memory it consumes.
  58. loopBatch int // how many entries to skip when emitting debug messages in a tight loop.
  59. noMemory, isServer, isShell bool // !isServer && !isShell => FastCGI!
  60. myDir, myPort, importFilename, database string
  61. configFilename string // name (+ path?) of the configuratio file.
  62. dbNamePath string // for BuntDB.
  63. logLevel, logFilename string // for logs.
  64. maxSize, maxBackups, maxAge int // logs configuration options.
  65. }
  66. var goslConfig goslConfigOptions // list of all configuration opions.
  67. var kv *badger.DB // current KV store being used (Badger).
  68. // loadConfiguration reads our configuration from a `config.ini` file,
  69. func loadConfiguration() {
  70. fmt.Println("Reading ", os.Args[0], " configuratiowwn:") // note that we might not have go-logging active as yet, so we use fmt and write to stdout
  71. // Open our config file and extract relevant data from there
  72. // Find and read the config file
  73. if err := viper.ReadInConfig(); err != nil {
  74. fmt.Printf("error reading config file %q, falling back to defaults - error was: %s\n", goslConfig.configFilename, err)
  75. // we fall back to what we have
  76. }
  77. // NOTE(gwyneth): the authors of say that 100000 is way too much for Badger.
  78. // Let's see what happens with BuntDB
  79. viper.SetDefault("config.BATCH_BLOCK", 100000)
  80. goslConfig.BATCH_BLOCK = viper.GetInt("config.BATCH_BLOCK")
  81. viper.SetDefault("config.loopBatch", 1000)
  82. goslConfig.loopBatch = viper.GetInt("config.loopBatch")
  83. viper.SetDefault("config.myPort", 3000)
  84. goslConfig.myPort = viper.GetString("config.myPort")
  85. viper.SetDefault("config.myDir", "slkvdb")
  86. goslConfig.myDir = viper.GetString("config.myDir")
  87. viper.SetDefault("config.isServer", false)
  88. goslConfig.isServer = viper.GetBool("config.isServer")
  89. viper.SetDefault("config.isShell", false)
  90. goslConfig.isShell = viper.GetBool("config.isShell")
  91. viper.SetDefault("config.database", "badger") // currently, badger, boltdb, leveldb.
  92. goslConfig.database = viper.GetString("config.database")
  93. viper.SetDefault("options.importFilename", "") // must be empty by default.
  94. goslConfig.importFilename = viper.GetString("options.importFilename")
  95. viper.SetDefault("options.noMemory", false)
  96. goslConfig.noMemory = viper.GetBool("options.noMemory")
  97. // Logging options
  98. viper.SetDefault("log.Filename", "gosl.log")
  99. goslConfig.logFilename = viper.GetString("log.Filename")
  100. viper.SetDefault("log.logLevel", "ERROR")
  101. goslConfig.logLevel = viper.GetString("log.logLevel")
  102. viper.SetDefault("log.MaxSize", 10)
  103. goslConfig.maxSize = viper.GetInt("log.MaxSize")
  104. viper.SetDefault("log.MaxBackups", 3)
  105. goslConfig.maxBackups = viper.GetInt("log.MaxBackups")
  106. viper.SetDefault("log.MaxAge", 28)
  107. goslConfig.maxAge = viper.GetInt("log.MaxAge")
  108. }
  109. // main() starts here.
  110. func main() {
  111. // Config viper, which reads in the configuration file every time it's needed.
  112. // Note that we need some hard-coded variables for the path and config file name.
  113. viper.SetDefault(goslConfig.configFilename, "config.ini")
  114. viper.SetConfigName(goslConfig.configFilename)
  115. // just to make sure; it's the same format as OpenSimulator (or MySQL) config files.
  116. viper.SetConfigType("ini")
  117. // optionally, look for config in the working directory.
  118. viper.AddConfigPath(".")
  119. // this is also a great place to put standard configurations:
  120. // NOTE:
  121. viper.AddConfigPath(filepath.Join("$HOME/.config/", os.Args[0]))
  122. // last chance — check on the usual place for Go source.
  123. viper.AddConfigPath("$HOME/go/src/git.gwynethllewelyn.net/GwynethLlewelyn/gosl-basics/")
  124. loadConfiguration()
  125. // Flag setup; can be overridden by config file.
  126. flag.StringVarP(&goslConfig.myPort, "port", "p", "3000", "Server port")
  127. flag.StringVar( &goslConfig.myDir, "dir", "slkvdb", "Directory where database files are stored")
  128. flag.BoolVar( &goslConfig.isServer, "server", false, "Run as server on port " + goslConfig.myPort)
  129. flag.BoolVar( &goslConfig.isShell, "shell", false, "Run as an interactive shell")
  130. flag.StringVarP(&goslConfig.importFilename, "import", "i", "", "Import database from W-Hat (use the csv.bz2 versions)")
  131. flag.StringVar( &goslConfig.configFilename, "config", "config.ini", "Configuration filename [extension defines type, INI by default]")
  132. flag.StringVar( &goslConfig.database, "database", "badger", "Database type [badger | buntdb | leveldb]")
  133. flag.BoolVar( &goslConfig.noMemory, "nomemory", true, "Attempt to use only disk to save memory on Badger (important for shared webservers)")
  134. flag.StringVarP(&goslConfig.logLevel, "debug", "d", "ERROR", "Logging level, e.g. one of [DEBUG | ERROR | NOTICE | INFO]")
  135. flag.IntVarP( &goslConfig.loopBatch, "loopbatch", "l", 1000, "How many entries to skip when emitting debug messages in a tight loop. Only useful when importing huge databases with high logging levels. Set to 1 if you wish to see logs for all entries.")
  136. flag.IntVarP( &goslConfig.BATCH_BLOCK, "batchblock", "b", 100000, "How many entries to write to the database as a block; the bigger, the faster, but the more memory it consumes.")
  137. // default is FastCGI
  138. flag.Parse()
  139. if err := viper.BindPFlags(flag.CommandLine); err != nil {
  140. fmt.Printf("error parsing/binding flags: %s\n", err)
  141. }
  142. if goslConfig.configFilename != "config.ini" {
  143. viper.SetConfigName(goslConfig.configFilename)
  144. // we can switch filetypes here
  145. ext := filepath.Ext(goslConfig.configFilename)[1:]
  146. viper.SetConfigType(ext)
  147. // Find and read the config fil
  148. if err := viper.ReadInConfig(); err != nil {
  149. fmt.Printf("error reading config file %q [type %s], falling back to defaults - error was: %s\n", goslConfig.configFilename, ext, err)
  150. // we fall back to what we have
  151. }
  152. }
  153. // Avoid division by zero...
  154. if goslConfig.BATCH_BLOCK < 1 {
  155. goslConfig.BATCH_BLOCK = 1
  156. }
  157. if goslConfig.loopBatch < 1 {
  158. goslConfig.loopBatch = 1
  159. }
  160. // this will allow our configuration file to be 'read on demand'
  161. // TODO(gwyneth): There is something broken with this, no reason why... (gwyneth 20211026)
  162. // viper.WatchConfig()
  163. // viper.OnConfigChange(func(e fsnotify.Event) {
  164. // if goslConfig.isServer || goslConfig.isShell {
  165. // fmt.Println("Config file changed:", e.Name) // BUG(gwyneth): FastCGI cannot write to output
  166. // }
  167. // loadConfiguration()
  168. // })
  169. // NOTE(gwyneth): We cannot write to stdout if we're running as FastCGI, only to logs!
  170. if goslConfig.isServer || goslConfig.isShell {
  171. fmt.Println(os.Args[0], " is starting...")
  172. }
  173. // This is mostly to deal with scoping issues below. (gwyneth 20211106)
  174. var err error
  175. // Setup the lumberjack rotating logger. This is because we need it for the go-logging logger when writing to files. (20170813)
  176. rotatingLogger := &lumberjack.Logger{
  177. Filename: goslConfig.logFilename,
  178. MaxSize: goslConfig.maxSize, // megabytes
  179. MaxBackups: goslConfig.maxBackups,
  180. MaxAge: goslConfig.maxAge, //days
  181. }
  182. // Set formatting for stderr and file (basically the same).
  183. 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
  184. // Setup the go-logging Logger. Do **not** log to stderr if running as FastCGI!
  185. backendFile := logging.NewLogBackend(rotatingLogger, "", 0)
  186. backendFileFormatter := logging.NewBackendFormatter(backendFile, logFormat)
  187. backendFileLeveled := logging.AddModuleLevel(backendFileFormatter)
  188. theLogLevel, err := logging.LogLevel(goslConfig.logLevel)
  189. if err != nil {
  190. log.Warningf("could not set log level to %q — invalid?\nlogging.LogLevel() returned error %q\n", goslConfig.logLevel, err)
  191. } else {
  192. log.Debugf("requested file log level: %q\n", theLogLevel.String())
  193. backendFileLeveled.SetLevel(theLogLevel, "gosl") // we just send debug data to logs if we run asshell
  194. log.Debugf("file log level set to: %v\n", backendFileLeveled.GetLevel("gosl"))
  195. }
  196. if goslConfig.isServer || goslConfig.isShell {
  197. backendStderr := logging.NewLogBackend(os.Stderr, "", 0)
  198. backendStderrFormatter := logging.NewBackendFormatter(backendStderr, logFormat)
  199. backendStderrLeveled := logging.AddModuleLevel(backendStderrFormatter)
  200. log.Debugf("requested stderr log level: %q\n", theLogLevel.String())
  201. backendStderrLeveled.SetLevel(theLogLevel, "gosl")
  202. log.Debugf("stderr log level set to: %v\n", backendStderrLeveled.GetLevel("gosl"))
  203. }
  204. /*
  205. // deprecated, now we set it explicitly if desired
  206. if goslConfig.isShell {
  207. backendStderrLeveled.SetLevel(logging.DEBUG, "gosl") // shell is meant to be for debugging mostly
  208. } else {
  209. backendStderrLeveled.SetLevel(logging.INFO, "gosl")
  210. }
  211. logging.SetBackend(backendStderrLeveled, backendFileLeveled)
  212. } else {
  213. logging.SetBackend(backendFileLeveled) // FastCGI only logs to file
  214. }
  215. */
  216. log.Debugf("Full config: %+v\n", goslConfig)
  217. // 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)
  218. if stat, err := os.Stat(goslConfig.myDir); err == nil && stat.IsDir() {
  219. // path is a valid directory
  220. log.Debugf("valid directory: %q\n", goslConfig.myDir)
  221. } else {
  222. // try to create directory
  223. if err = os.Mkdir(goslConfig.myDir, 0700); err != nil {
  224. if !os.IsExist(err) {
  225. checkErr(err)
  226. } else {
  227. log.Debugf("directory %q exists, no need to create it\n", goslConfig.myDir)
  228. }
  229. }
  230. log.Debugf("created new directory: %q\n", goslConfig.myDir)
  231. }
  232. // Special options configuration.
  233. // Currently, this is only needed for Badger v3, the others have much simpler configurations.
  234. // (gwyneth 20211106)
  235. switch goslConfig.database {
  236. case "badger":
  237. // Badger v3 - fully rewritten configuration (much simpler!!) (gwyneth 20211026)
  238. if goslConfig.noMemory {
  239. // use disk; note that unlike the others, Badger generates its own filenames,
  240. // we can only pass a _directory_... (gwyneth 20211027)
  241. goslConfig.dbNamePath = filepath.Join(goslConfig.myDir, databaseName)
  242. // try to create directory
  243. if err = os.Mkdir(goslConfig.dbNamePath, 0700); err != nil {
  244. if err != os.ErrExist {
  245. checkErr(err)
  246. } else {
  247. log.Debugf("directory %q exists, no need to create it\n", goslConfig.dbNamePath)
  248. }
  249. } else {
  250. log.Debugf("created new directory: %q\n", goslConfig.dbNamePath)
  251. }
  252. Opt = badger.DefaultOptions(goslConfig.dbNamePath)
  253. log.Debugf("entering disk mode, Opt is %+v\n", Opt)
  254. } else {
  255. // Use only memory
  256. Opt = badger.LSMOnlyOptions("").WithInMemory(true)
  257. Opt.WithLevelSizeMultiplier(1)
  258. Opt.WithNumMemtables(1)
  259. Opt.WithValueDir(Opt.Dir) // probably not needed
  260. log.Debugf("entering memory-only mode, Opt is %+v\n", Opt)
  261. }
  262. // common config
  263. Opt.WithLogger(log) // set the internal logger to our own rotating logger
  264. Opt.WithLoggingLevel(badger.ERROR)
  265. goslConfig.BATCH_BLOCK = 1000 // try to import less at each time, it will take longer but hopefully work
  266. log.Info("trying to avoid too much memory consumption")
  267. // the other databases do not require any special configuration (for now)
  268. } // /switch
  269. // if importFilename isn't empty, this means we potentially have something to import.
  270. if goslConfig.importFilename != "" {
  271. log.Info("attempting to import", goslConfig.importFilename, "...")
  272. importDatabase(goslConfig.importFilename)
  273. log.Info("database finished import.")
  274. } else {
  275. // it's not an error if there is no name2key database available for import (gwyneth 20211027)
  276. log.Debug("no database configured for import — 🆗")
  277. }
  278. // Prepare testing data! (common to all database types)
  279. // Note: this only works for shell/server; for FastCGI it's definitely overkill (gwyneth 20211106),
  280. // so we do it only for server/shell mode.
  281. if goslConfig.isServer || goslConfig.isShell {
  282. const testAvatarName = "Nobody Here"
  283. log.Infof("%s started and logging is set up. Proceeding to test database (%s) at %q\n", os.Args[0], goslConfig.database, goslConfig.myDir)
  284. // generate a random UUID (gwyneth2021103) (gwyneth 20211031)
  285. var (
  286. testUUID = uuid.New().String() // Random UUID (gwyneth 20211031 — from )
  287. testValue = avatarUUID{testAvatarName, testUUID, "all grids"}
  288. )
  289. jsonTestValue, err := json.Marshal(testValue)
  290. checkErrPanic(err) // something went VERY wrong
  291. // KVDB Initialisation & Tests
  292. // Each case is different
  293. switch goslConfig.database {
  294. case "badger":
  295. // Opt has already been set earlier. (gwyneth 20211106)
  296. kv, err := badger.Open(Opt)
  297. checkErrPanic(err) // should probably panic, cannot prep new database
  298. txn := kv.NewTransaction(true)
  299. err = txn.Set([]byte(testAvatarName), jsonTestValue)
  300. checkErrPanic(err)
  301. err = txn.Set([]byte(testUUID), jsonTestValue)
  302. checkErrPanic(err)
  303. err = txn.Commit()
  304. checkErrPanic(err)
  305. log.Debugf("badger SET %+v (json: %v)\n", testValue, string(jsonTestValue))
  306. kv.Close()
  307. case "buntdb":
  308. goslConfig.dbNamePath = filepath.Join(goslConfig.myDir, databaseName)
  309. db, err := buntdb.Open(goslConfig.dbNamePath)
  310. checkErrPanic(err)
  311. err = db.Update(func(tx *buntdb.Tx) error {
  312. _, _, err := tx.Set(testAvatarName, string(jsonTestValue), nil)
  313. return err
  314. })
  315. checkErr(err)
  316. log.Debugf("buntdb SET %+v (json: %v)\n", testValue, string(jsonTestValue))
  317. db.Close()
  318. case "leveldb":
  319. goslConfig.dbNamePath = filepath.Join(goslConfig.myDir, databaseName)
  320. db, err := leveldb.OpenFile(goslConfig.dbNamePath, nil)
  321. checkErrPanic(err)
  322. err = db.Put([]byte(testAvatarName), jsonTestValue, nil)
  323. checkErrPanic(err)
  324. log.Debugf("leveldb SET %+v (json: %v)\n", testValue, string(jsonTestValue))
  325. db.Close()
  326. } // /switch
  327. // common to all databases:
  328. key, grid := searchKVname(testAvatarName)
  329. log.Debugf("GET %q returned %q [grid %q]\n", testAvatarName, key, grid)
  330. log.Info("KV database seems fine.")
  331. if goslConfig.importFilename != "" {
  332. log.Info("attempting to import", goslConfig.importFilename, "...")
  333. importDatabase(goslConfig.importFilename)
  334. log.Info("database finished import.")
  335. } else {
  336. // it's not an error if there is no name2key database available for import (gwyneth 20211027)
  337. log.Debug("no database configured for import")
  338. }
  339. }
  340. if goslConfig.isShell {
  341. log.Info("starting to run as interactive shell")
  342. fmt.Println("Ctrl-C to quit, or just type \"quit\".")
  343. var err error // to avoid assigning text in a different scope (this is a bit awkward, but that's the problem with bi-assignment)
  344. var avatarName, avatarKey, gridName string
  345. rl, err := readline.New("enter avatar name or UUID: ")
  346. if err != nil {
  347. log.Criticalf("major readline issue preventing normal functioning; error was %q\n", err)
  348. }
  349. defer rl.Close()
  350. for {
  351. checkInput, err := rl.Readline()
  352. if err != nil || checkInput == "quit" { // io.EOF
  353. break
  354. }
  355. checkInput = strings.TrimRight(checkInput, "\r\n")
  356. // fmt.Printf("Ok, got %s length is %d and UUID is %v\n", checkInput, len(checkInput), isValidUUID(checkInput))
  357. if (len(checkInput) == 36) && isValidUUID(checkInput) {
  358. avatarName, gridName = searchKVUUID(checkInput)
  359. avatarKey = checkInput
  360. } else {
  361. avatarKey, gridName = searchKVname(checkInput)
  362. avatarName = checkInput
  363. }
  364. if avatarName != NullUUID && avatarKey != NullUUID {
  365. fmt.Println(avatarName, "which has UUID:", avatarKey, "comes from grid:", gridName)
  366. } else {
  367. fmt.Println("sorry, unknown input", checkInput)
  368. }
  369. }
  370. // never leaves until Ctrl-C or by typing `quit`. (gwyneth 20211106)
  371. log.Debug("interactive session finished.")
  372. os.Exit(0) // normal exit
  373. } else if goslConfig.isServer {
  374. // set up routing.
  375. // NOTE(gwyneth): one function only because FastCGI seems to have problems with multiple handlers.
  376. http.HandleFunc("/", handler)
  377. log.Debug("directory for database:", goslConfig.myDir)
  378. log.Info("starting to run as web server on port :" + goslConfig.myPort)
  379. err := http.ListenAndServe(":"+goslConfig.myPort, nil) // set listen port
  380. checkErrPanic(err) // if it can't listen to all the above, then it has to abort anyway
  381. } else {
  382. // default is to run as FastCGI!
  383. // works like a charm thanks to http://www.dav-muz.net/blog/2013/09/how-to-use-go-and-fastcgi/
  384. log.Debug("http.DefaultServeMux is", http.DefaultServeMux)
  385. log.Info("Starting to run as FastCGI")
  386. if err := fcgi.Serve(nil, http.HandlerFunc(handler)); err != nil {
  387. log.Errorf("seems that we got an error from FCGI: %q\n", err)
  388. checkErrPanic(err)
  389. }
  390. }
  391. // we should never have reached this point!
  392. log.Error("unknown usage — this application may run as a standalone server, as a FastCGI application, or as an interactive shell")
  393. if goslConfig.isServer || goslConfig.isShell {
  394. flag.PrintDefaults()
  395. }
  396. }
  397. // handler deals with incoming queries and/or associates avatar names with keys depending on parameters.
  398. // Basically we check if both an avatar name and a UUID key has been received: if yes, this means a new entry;
  399. // - if just the avatar name was received, it means looking up its key;
  400. // - if just the key was received, it means looking up the name (not necessary since llKey2Name does that, but it's just to illustrate);
  401. // - if nothing is received, then return an error.
  402. //
  403. // Note: to ensure quick lookups, we actually set *two* key/value pairs, one with avatar name/UUID,
  404. // the other with UUID/name — that way, we can efficiently search for *both* in the same database!
  405. // Theoretically, we could even have *two* KV databases, but that's too much trouble for the
  406. // sake of some extra efficiency. (gwyneth 20211030)
  407. func handler(w http.ResponseWriter, r *http.Request) {
  408. if err := r.ParseForm(); err != nil {
  409. logErrHTTP(w, http.StatusNotFound, "no avatar and/or UUID received")
  410. return
  411. }
  412. // test first if this comes from Second Life or OpenSimulator
  413. /*
  414. if r.Header.Get("X-Secondlife-Region") == "" {
  415. logErrHTTP(w, http.StatusForbidden, "Sorry, this application only works inside Second Life.")
  416. return
  417. }
  418. */
  419. name := r.Form.Get("name") // can be empty.
  420. key := r.Form.Get("key") // can be empty.
  421. compat := r.Form.Get("compat") // compatibility mode with W-Hat,
  422. var uuidToInsert avatarUUID
  423. messageToSL := "" // this is what we send back to SL - defined here due to scope issues.
  424. if name != "" {
  425. if key != "" {
  426. // we received both: add a new entry.
  427. uuidToInsert.UUID = key
  428. uuidToInsert.Grid = r.Header.Get("X-Secondlife-Shard")
  429. jsonUUIDToInsert, err := json.Marshal(uuidToInsert)
  430. checkErr(err)
  431. switch goslConfig.database {
  432. case "badger":
  433. kv, err := badger.Open(Opt)
  434. checkErrPanic(err) // should probably panic.
  435. txn := kv.NewTransaction(true)
  436. defer txn.Discard()
  437. err = txn.Set([]byte(name), jsonUUIDToInsert)
  438. checkErrPanic(err)
  439. err = txn.Commit()
  440. checkErrPanic(err)
  441. kv.Close()
  442. case "buntdb":
  443. db, err := buntdb.Open(goslConfig.dbNamePath)
  444. checkErrPanic(err)
  445. defer db.Close()
  446. err = db.Update(func(tx *buntdb.Tx) error {
  447. _, _, err := tx.Set(name, string(jsonUUIDToInsert), nil)
  448. return err
  449. })
  450. checkErr(err)
  451. case "leveldb":
  452. db, err := leveldb.OpenFile(goslConfig.dbNamePath, nil)
  453. checkErrPanic(err)
  454. err = db.Put([]byte(name), jsonUUIDToInsert, nil)
  455. checkErrPanic(err)
  456. db.Close()
  457. }
  458. messageToSL += "Added new entry for '" + name + "' which is: " + uuidToInsert.UUID + " from grid: '" + uuidToInsert.Grid + "'"
  459. } else {
  460. // we received a name: look up its UUID key and grid.
  461. key, grid := searchKVname(name)
  462. if compat == "false" {
  463. messageToSL += "UUID for '" + name + "' is: " + key + " from grid: '" + grid + "'"
  464. } else { // empty also means true!
  465. messageToSL += key
  466. }
  467. }
  468. } else if key != "" {
  469. // in this scenario, we have the UUID key but no avatar name: do the equivalent of a llKey2Name
  470. name, grid := searchKVUUID(key)
  471. if compat == "false" {
  472. messageToSL += "avatar name for " + key + "' is '" + name + "' on grid: '" + grid + "'"
  473. } else { // empty also means true!
  474. messageToSL += name
  475. }
  476. } else {
  477. // neither UUID key nor avatar received, this is an error
  478. logErrHTTP(w, http.StatusNotFound, "empty avatar name and UUID key received, cannot proceed")
  479. return
  480. }
  481. w.WriteHeader(http.StatusOK)
  482. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  483. fmt.Fprint(w, messageToSL)
  484. }