gosl.go 18 KB

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