gosl.go 15 KB

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