1
0

gosl.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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/op/go-logging"
  13. "gopkg.in/natefinch/lumberjack.v2"
  14. "io"
  15. "net/http"
  16. "net/http/fcgi"
  17. "os"
  18. "path/filepath"
  19. "regexp"
  20. "runtime"
  21. "strings"
  22. "time"
  23. )
  24. const NullUUID = "00000000-0000-0000-0000-000000000000" // always useful when we deal with SL/OpenSimulator...
  25. // Logging setup.
  26. var log = logging.MustGetLogger("gosl") // configuration for the go-logging logger, must be available everywhere
  27. var logFormat logging.Formatter
  28. // Opt is used for KV database setup.
  29. var Opt badger.Options
  30. // AvatarUUID is the type that we store in the database; we keep a record from which grid it came from.
  31. type avatarUUID struct {
  32. UUID string // needs to be capitalised for JSON marshalling (it has to do with the way it works)
  33. Grid string
  34. }
  35. var BATCH_BLOCK = 1000000 // how many entries to write to the database as a block; the bigger, the faster, but the more memory it consumes
  36. // the authors say that 100000 is way too much
  37. /*
  38. .__
  39. _____ _____ |__| ____
  40. / \\__ \ | |/ \
  41. | Y Y \/ __ \| | | \
  42. |__|_| (____ /__|___| /
  43. \/ \/ \/
  44. */
  45. var noMemory *bool
  46. // main() starts here.
  47. func main() {
  48. // Flag setup
  49. var myPort = flag.String("port", "3000", "Server port")
  50. var myDir = flag.String("dir", "slkvdb", "Directory where database files are stored")
  51. var isServer = flag.Bool("server", false, "Run as server on port " + *myPort)
  52. var isShell = flag.Bool("shell", false, "Run as an interactive shell")
  53. var importFilename = flag.String("import", "", "Import database from W-Hat (use the csv.bz2 version)")
  54. noMemory = flag.Bool("nomemory", false, "Attempt to use only disk to save memory (important for shared webservers)")
  55. // default is FastCGI
  56. flag.Parse()
  57. // We cannot write to stdout if we're running as FastCGI, only to logs!
  58. if *isServer || *isShell {
  59. fmt.Println("gosl is starting...")
  60. } else { // FastCGI: we cannot write to stdio, we need to setup the logger so that we can write to disk
  61. *noMemory = true
  62. }
  63. // Setup the lumberjack rotating logger. This is because we need it for the go-logging logger when writing to files. (20170813)
  64. rotatingLogger := &lumberjack.Logger{
  65. Filename: "gosl.log",
  66. MaxSize: 10, // megabytes
  67. MaxBackups: 3,
  68. MaxAge: 28, //days
  69. }
  70. // Set formatting for stderr and file (basically the same).
  71. 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
  72. // Setup the go-logging Logger. Do **not** log to stderr if running as FastCGI!
  73. backendFile := logging.NewLogBackend(rotatingLogger, "", 0)
  74. backendFileFormatter := logging.NewBackendFormatter(backendFile, logFormat)
  75. backendFileLeveled := logging.AddModuleLevel(backendFileFormatter)
  76. backendFileLeveled.SetLevel(logging.INFO, "gosl") // we just send debug data to logs if we run as shell
  77. if *isServer || *isShell {
  78. backendStderr := logging.NewLogBackend(os.Stderr, "", 0)
  79. backendStderrFormatter := logging.NewBackendFormatter(backendStderr, logFormat)
  80. backendStderrLeveled := logging.AddModuleLevel(backendStderrFormatter)
  81. if *isShell {
  82. backendStderrLeveled.SetLevel(logging.DEBUG, "gosl") // shell is meant to be for debugging mostly
  83. } else {
  84. backendStderrLeveled.SetLevel(logging.INFO, "gosl")
  85. }
  86. logging.SetBackend(backendStderrLeveled, backendFileLeveled)
  87. } else {
  88. logging.SetBackend(backendFileLeveled) // FastCGI only logs to file
  89. }
  90. Opt = badger.DefaultOptions
  91. // 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
  92. if stat, err := os.Stat(*myDir); err == nil && stat.IsDir() {
  93. // path is a valid directory
  94. log.Infof("Valid directory: %s\n", *myDir)
  95. } else {
  96. // try to create directory
  97. err = os.Mkdir(*myDir, 0700)
  98. checkErrPanic(err) // cannot make directory, panic and exit logging what went wrong
  99. log.Debugf("Created new directory: %s\n", *myDir)
  100. }
  101. Opt.Dir = *myDir
  102. Opt.ValueDir = Opt.Dir
  103. Opt.TableLoadingMode = options.MemoryMap
  104. //Opt.TableLoadingMode = options.FileIO
  105. if *noMemory {
  106. // Opt.TableLoadingMode = options.FileIO // use standard file I/O operations for tables instead of LoadRAM
  107. // Opt.TableLoadingMode = options.MemoryMap // MemoryMap indicates that that the file must be memory-mapped - https://github.com/dgraph-io/badger/issues/224#issuecomment-329643771
  108. Opt.TableLoadingMode = options.FileIO
  109. Opt.ValueLogFileSize = 1048576
  110. BATCH_BLOCK = 1000 // try to import less at each time, it will take longer but hopefully work
  111. log.Info("Trying to avoid too much memory consumption")
  112. }
  113. //if *isShell {
  114. // Do some testing to see if the database is available
  115. const testAvatarName = "Nobody Here"
  116. var err error
  117. log.Info("gosl started and logging is set up. Proceeding to test KV database.")
  118. kv, err := badger.Open(Opt)
  119. checkErrPanic(err) // should probably panic, cannot prep new database
  120. var testValue = avatarUUID{ NullUUID, "all grids" }
  121. jsonTestValue, err := json.Marshal(testValue)
  122. checkErrPanic(err) // something went VERY wrong
  123. txn := kv.NewTransaction(true)
  124. err = txn.Set([]byte(testAvatarName), jsonTestValue, 0x00)
  125. checkErrPanic(err)
  126. err = txn.Commit(nil)
  127. checkErrPanic(err)
  128. log.Debugf("SET %+v (json: %v)\n", testValue, string(jsonTestValue))
  129. kv.Close()
  130. key, grid := searchKVname(testAvatarName)
  131. log.Debugf("GET '%s' returned '%s' [grid '%s']\n", testAvatarName, key, grid)
  132. log.Info("KV database seems fine.")
  133. //}
  134. if *importFilename != "" {
  135. log.Info("Attempting to import", *importFilename, "...")
  136. importDatabase(*importFilename)
  137. log.Info("Database finished import.")
  138. }
  139. if *isShell {
  140. log.Info("Starting to run as interactive shell")
  141. reader := bufio.NewReader(os.Stdin)
  142. fmt.Println("Ctrl-C to quit.")
  143. var err error // to avoid assigning text in a different scope (this is a bit awkward, but that's the problem with bi-assignment)
  144. var checkInput, avatarName, avatarKey, gridName string
  145. for {
  146. // Prompt and read
  147. fmt.Print("Enter avatar name or UUID: ")
  148. checkInput, err = reader.ReadString('\n')
  149. checkErr(err)
  150. checkInput = strings.TrimRight(checkInput, "\r\n")
  151. // fmt.Printf("Ok, got %s length is %d and UUID is %v\n", checkInput, len(checkInput), isValidUUID(checkInput))
  152. if (len(checkInput) == 36) && isValidUUID(checkInput) {
  153. avatarName, gridName = searchKVUUID(checkInput)
  154. avatarKey = checkInput
  155. } else {
  156. avatarKey, gridName = searchKVname(checkInput)
  157. avatarName = checkInput
  158. }
  159. if avatarName != NullUUID && avatarKey != NullUUID {
  160. fmt.Println(avatarName, "which has UUID:", avatarKey, "comes from grid:", gridName)
  161. } else {
  162. fmt.Println("Sorry, unknown input", checkInput)
  163. }
  164. }
  165. // never leaves until Ctrl-C
  166. }
  167. // set up routing.
  168. // NOTE(gwyneth): one function only because FastCGI seems to have problems with multiple handlers.
  169. http.HandleFunc("/", handler)
  170. log.Info("Directory for database:", *myDir)
  171. if (*isServer) {
  172. log.Info("Starting to run as web server on port " + *myPort)
  173. err := http.ListenAndServe(":" + *myPort, nil) // set listen port
  174. checkErrPanic(err) // if it can't listen to all the above, then it has to abort anyway
  175. } else {
  176. // default is to run as FastCGI!
  177. // works like a charm thanks to http://www.dav-muz.net/blog/2013/09/how-to-use-go-and-fastcgi/
  178. log.Debug("http.DefaultServeMux is", http.DefaultServeMux)
  179. if err := fcgi.Serve(nil, nil); err != nil {
  180. checkErrPanic(err)
  181. }
  182. }
  183. // we should never have reached this point!
  184. log.Error("Unknown usage! This application may run as a standalone server, as FastCGI application, or as an interactive shell")
  185. if *isServer || *isShell {
  186. flag.PrintDefaults()
  187. }
  188. }
  189. // handler deals with incoming queries and/or associates avatar names with keys depending on parameters.
  190. // Basically we check if both an avatar name and a UUID key has been received: if yes, this means a new entry;
  191. // if just the avatar name was received, it means looking up its key;
  192. // if just the key was received, it means looking up the name (not necessary since llKey2Name does that, but it's just to illustrate);
  193. // if nothing is received, then return an error
  194. func handler(w http.ResponseWriter, r *http.Request) {
  195. if err := r.ParseForm(); err != nil {
  196. logErrHTTP(w, http.StatusNotFound, "No avatar and/or UUID received")
  197. return
  198. }
  199. // test first if this comes from Second Life or OpenSimulator
  200. /*
  201. if r.Header.Get("X-Secondlife-Region") == "" {
  202. logErrHTTP(w, http.StatusForbidden, "Sorry, this application only works inside Second Life.")
  203. return
  204. }
  205. */
  206. name := r.Form.Get("name") // can be empty
  207. key := r.Form.Get("key") // can be empty
  208. compat := r.Form.Get("compat") // compatibility mode with W-Hat
  209. var valueToInsert avatarUUID
  210. messageToSL := "" // this is what we send back to SL - defined here due to scope issues.
  211. if name != "" {
  212. if key != "" {
  213. // we received both: add a new entry
  214. kv, err := badger.Open(Opt)
  215. checkErrPanic(err) // should probably panic
  216. valueToInsert.UUID = key
  217. valueToInsert.Grid = r.Header.Get("X-Secondlife-Shard")
  218. jsonValueToInsert, err := json.Marshal(valueToInsert)
  219. checkErr(err)
  220. txn := kv.NewTransaction(true)
  221. defer txn.Discard()
  222. err = txn.Set([]byte(name), jsonValueToInsert, 0x00)
  223. checkErrPanic(err)
  224. err = txn.Commit(nil)
  225. checkErrPanic(err)
  226. kv.Close()
  227. messageToSL += "Added new entry for '" + name + "' which is: " + valueToInsert.UUID + " from grid: '" + valueToInsert.Grid + "'"
  228. } else {
  229. // we received a name: look up its UUID key and grid.
  230. key, grid := searchKVname(name)
  231. if compat == "false" {
  232. messageToSL += "UUID for '" + name + "' is: " + key + " from grid: '" + grid + "'"
  233. } else { // empty also means true!
  234. messageToSL += key
  235. }
  236. }
  237. } else if key != "" {
  238. // in this scenario, we have the UUID key but no avatar name: do the equivalent of a llKey2Name (slow)
  239. name, grid := searchKVUUID(key)
  240. if compat == "false" {
  241. messageToSL += "Avatar name for " + key + "' is '" + name + "' on grid: '" + grid + "'"
  242. } else { // empty also means true!
  243. messageToSL += name
  244. }
  245. } else {
  246. // neither UUID key nor avatar received, this is an error
  247. logErrHTTP(w, http.StatusNotFound, "Empty avatar name and UUID key received, cannot proceed")
  248. return
  249. }
  250. w.WriteHeader(http.StatusOK)
  251. w.Header().Set("Content-type", "text/plain; charset=utf-8")
  252. fmt.Fprintf(w, messageToSL)
  253. }
  254. // searchKVname searches the KV database for an avatar name.
  255. func searchKVname(avatarName string) (UUID string, grid string) {
  256. time_start := time.Now()
  257. kv, err := badger.Open(Opt)
  258. defer kv.Close()
  259. // var item badger.Item
  260. var val = avatarUUID{ NullUUID, "" }
  261. // txn := kv.NewTransaction(true)
  262. // defer txn.Discard()
  263. err = kv.View(func(txn *badger.Txn) error {
  264. item, err := txn.Get([]byte(avatarName))
  265. if err != nil {
  266. return err
  267. }
  268. data, err := item.Value()
  269. if err != nil {
  270. log.Errorf("Error '%s' while getting data from %v\n", err, item)
  271. return err
  272. }
  273. err = json.Unmarshal(data, &val)
  274. if err != nil {
  275. log.Errorf("Error while unparsing UUID for name: '%s' (%v)\n", avatarName, err)
  276. return err
  277. }
  278. return nil
  279. })
  280. if err != nil {
  281. return NullUUID, ""
  282. }
  283. time_end := time.Now()
  284. diffTime := time_end.Sub(time_start)
  285. log.Debugf("Time to lookup '%s': %v\n", avatarName, diffTime)
  286. return val.UUID, val.Grid
  287. }
  288. // searchKVUUID searches the KV database for an avatar key.
  289. func searchKVUUID(avatarKey string) (name string, grid string) {
  290. time_start := time.Now()
  291. kv, err := badger.Open(Opt)
  292. checkErr(err) // should probably panic
  293. itOpt := badger.DefaultIteratorOptions
  294. if !*noMemory {
  295. itOpt.PrefetchValues = true
  296. itOpt.PrefetchSize = 1000 // attempt to get this a little bit more efficient; we have many small entries, so this is not too much
  297. } else {
  298. itOpt.PrefetchValues = false
  299. }
  300. checks := 0
  301. var val = avatarUUID{ NullUUID, "" }
  302. var found string
  303. txn := kv.NewTransaction(true)
  304. defer txn.Discard()
  305. err = kv.View(func(txn *badger.Txn) error {
  306. itr := txn.NewIterator(itOpt)
  307. defer itr.Close()
  308. for itr.Rewind(); itr.Valid(); itr.Next() {
  309. item := itr.Item()
  310. data, err := item.Value()
  311. if err != nil {
  312. log.Errorf("Error '%s' while getting data from %v\n", err, item)
  313. return err
  314. }
  315. err = json.Unmarshal(data, &val)
  316. if err != nil {
  317. log.Errorf("Error '%s' while unparsing UUID for data: %v\n", err, data)
  318. return err
  319. }
  320. checks++ //Just to see how many checks we made, for statistical purposes
  321. if avatarKey == val.UUID {
  322. found = string(item.Key())
  323. break
  324. }
  325. }
  326. return nil
  327. })
  328. time_end := time.Now()
  329. diffTime := time_end.Sub(time_start)
  330. log.Debugf("Made %d checks for '%s' in %v\n", checks, avatarKey, diffTime)
  331. kv.Close()
  332. return found, val.Grid
  333. }
  334. // importDatabase is essentially reading a bzip2'ed CSV file with UUID,AvatarName downloaded from http://w-hat.com/#name2key .
  335. // One could theoretically set a cron job to get this file, save it on disk periodically, and keep the database up-to-date
  336. // see https://stackoverflow.com/questions/24673335/how-do-i-read-a-gzipped-csv-file for the actual usage of these complicated things!
  337. func importDatabase(filename string) {
  338. filehandler, err := os.Open(filename)
  339. if err != nil {
  340. log.Fatal(err)
  341. }
  342. defer filehandler.Close()
  343. gr := bzip2.NewReader(filehandler) // open bzip2 reader
  344. cr := csv.NewReader(gr) // open csv reader and feed the bzip2 reader into it
  345. // prepare connection to KV database
  346. kv, err := badger.Open(Opt)
  347. checkErrPanic(err) // should probably panic
  348. defer kv.Close()
  349. time_start := time.Now() // we want to get an idea on how long this takes
  350. limit := 0 // outside of for loop so that we can count how many entries we had in total
  351. txn := kv.NewTransaction(true) // start new transaction; we will commit only every BATCH_BLOCK entries
  352. defer txn.Discard()
  353. for ;;limit++ {
  354. record, err := cr.Read()
  355. if err == io.EOF {
  356. break
  357. } else if err != nil {
  358. log.Fatal(err)
  359. }
  360. jsonNewEntry, err := json.Marshal(avatarUUID{ record[0], "Production" }) // W-Hat keys come all from the main LL grid, known as 'Production'
  361. if err != nil {
  362. log.Warning(err)
  363. } else {
  364. err = txn.Set([]byte(record[1]), jsonNewEntry, 0x00)
  365. if err != nil {
  366. log.Fatal(err)
  367. }
  368. }
  369. if limit % BATCH_BLOCK == 0 && limit != 0 { // we do not run on the first time, and then only every BATCH_BLOCK times
  370. log.Info("Processing:", limit)
  371. err = txn.Commit(nil)
  372. if err != nil {
  373. log.Fatal(err)
  374. }
  375. txn = kv.NewTransaction(true) // start a new transaction
  376. defer txn.Discard()
  377. }
  378. }
  379. // commit last batch
  380. err = txn.Commit(nil)
  381. if err != nil {
  382. log.Fatal(err)
  383. }
  384. kv.PurgeOlderVersions()
  385. time_end := time.Now()
  386. diffTime := time_end.Sub(time_start)
  387. log.Info("Total read", limit, "records (or thereabouts) in", diffTime)
  388. }
  389. // NOTE(gwyneth):Auxiliary functions which I'm always using...
  390. // checkErrPanic logs a fatal error and panics.
  391. func checkErrPanic(err error) {
  392. if err != nil {
  393. pc, file, line, ok := runtime.Caller(1)
  394. log.Panic(filepath.Base(file), ":", line, ":", pc, ok, " - panic:", err)
  395. }
  396. }
  397. // checkErr checks if there is an error, and if yes, it logs it out and continues.
  398. // this is for 'normal' situations when we want to get a log if something goes wrong but do not need to panic
  399. func checkErr(err error) {
  400. if err != nil {
  401. pc, file, line, ok := runtime.Caller(1)
  402. log.Error(filepath.Base(file), ":", line, ":", pc, ok, " - error:", err)
  403. }
  404. }
  405. // Auxiliary functions for HTTP handling
  406. // checkErrHTTP returns an error via HTTP and also logs the error.
  407. func checkErrHTTP(w http.ResponseWriter, httpStatus int, errorMessage string, err error) {
  408. if err != nil {
  409. http.Error(w, fmt.Sprintf(errorMessage, err), httpStatus)
  410. pc, file, line, ok := runtime.Caller(1)
  411. log.Error("(", http.StatusText(httpStatus), ") ", filepath.Base(file), ":", line, ":", pc, ok, " - error:", errorMessage, err)
  412. }
  413. }
  414. // checkErrPanicHTTP returns an error via HTTP and logs the error with a panic.
  415. func checkErrPanicHTTP(w http.ResponseWriter, httpStatus int, errorMessage string, err error) {
  416. if err != nil {
  417. http.Error(w, fmt.Sprintf(errorMessage, err), httpStatus)
  418. pc, file, line, ok := runtime.Caller(1)
  419. log.Panic("(", http.StatusText(httpStatus), ") ", filepath.Base(file), ":", line, ":", pc, ok, " - panic:", errorMessage, err)
  420. }
  421. }
  422. // logErrHTTP assumes that the error message was already composed and writes it to HTTP and logs it.
  423. // this is mostly to avoid code duplication and make sure that all entries are written similarly
  424. func logErrHTTP(w http.ResponseWriter, httpStatus int, errorMessage string) {
  425. http.Error(w, errorMessage, httpStatus)
  426. log.Error("(" + http.StatusText(httpStatus) + ") " + errorMessage)
  427. }
  428. // funcName is @Sonia's solution to get the name of the function that Go is currently running.
  429. // This will be extensively used to deal with figuring out where in the code the errors are!
  430. // Source: https://stackoverflow.com/a/10743805/1035977 (20170708)
  431. func funcName() string {
  432. pc, _, _, _ := runtime.Caller(1)
  433. return runtime.FuncForPC(pc).Name()
  434. }
  435. // isValidUUID checks if the UUID is valid.
  436. // Thanks to Patrick D'Appollonio https://stackoverflow.com/questions/25051675/how-to-validate-uuid-v4-in-go
  437. func isValidUUID(uuid string) bool {
  438. 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}$")
  439. return r.MatchString(uuid)
  440. }