gosl.go 20 KB

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