init.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "html/template"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strings"
  10. "syscall"
  11. "time"
  12. "github.com/jmoiron/sqlx"
  13. "github.com/jmoiron/sqlx/types"
  14. "github.com/knadh/goyesql/v2"
  15. goyesqlx "github.com/knadh/goyesql/v2/sqlx"
  16. "github.com/knadh/koanf"
  17. "github.com/knadh/koanf/maps"
  18. "github.com/knadh/koanf/parsers/toml"
  19. "github.com/knadh/koanf/providers/confmap"
  20. "github.com/knadh/koanf/providers/file"
  21. "github.com/knadh/koanf/providers/posflag"
  22. "github.com/knadh/listmonk/internal/bounce"
  23. "github.com/knadh/listmonk/internal/bounce/mailbox"
  24. "github.com/knadh/listmonk/internal/i18n"
  25. "github.com/knadh/listmonk/internal/manager"
  26. "github.com/knadh/listmonk/internal/media"
  27. "github.com/knadh/listmonk/internal/media/providers/filesystem"
  28. "github.com/knadh/listmonk/internal/media/providers/s3"
  29. "github.com/knadh/listmonk/internal/messenger"
  30. "github.com/knadh/listmonk/internal/messenger/email"
  31. "github.com/knadh/listmonk/internal/messenger/postback"
  32. "github.com/knadh/listmonk/internal/subimporter"
  33. "github.com/knadh/stuffbin"
  34. "github.com/labstack/echo"
  35. flag "github.com/spf13/pflag"
  36. )
  37. const (
  38. queryFilePath = "queries.sql"
  39. // Root URI of the admin frontend.
  40. adminRoot = "/admin"
  41. )
  42. // constants contains static, constant config values required by the app.
  43. type constants struct {
  44. RootURL string `koanf:"root_url"`
  45. LogoURL string `koanf:"logo_url"`
  46. FaviconURL string `koanf:"favicon_url"`
  47. FromEmail string `koanf:"from_email"`
  48. NotifyEmails []string `koanf:"notify_emails"`
  49. EnablePublicSubPage bool `koanf:"enable_public_subscription_page"`
  50. Lang string `koanf:"lang"`
  51. DBBatchSize int `koanf:"batch_size"`
  52. Privacy struct {
  53. IndividualTracking bool `koanf:"individual_tracking"`
  54. AllowBlocklist bool `koanf:"allow_blocklist"`
  55. AllowExport bool `koanf:"allow_export"`
  56. AllowWipe bool `koanf:"allow_wipe"`
  57. Exportable map[string]bool `koanf:"-"`
  58. } `koanf:"privacy"`
  59. AdminUsername []byte `koanf:"admin_username"`
  60. AdminPassword []byte `koanf:"admin_password"`
  61. UnsubURL string
  62. LinkTrackURL string
  63. ViewTrackURL string
  64. OptinURL string
  65. MessageURL string
  66. MediaProvider string
  67. BounceWebhooksEnabled bool
  68. BounceSESEnabled bool
  69. BounceSendgridEnabled bool
  70. }
  71. func initFlags() {
  72. f := flag.NewFlagSet("config", flag.ContinueOnError)
  73. f.Usage = func() {
  74. // Register --help handler.
  75. fmt.Println(f.FlagUsages())
  76. os.Exit(0)
  77. }
  78. // Register the commandline flags.
  79. f.StringSlice("config", []string{"config.toml"},
  80. "path to one or more config files (will be merged in order)")
  81. f.Bool("install", false, "setup database (first time)")
  82. f.Bool("idempotent", false, "make --install run only if the databse isn't already setup")
  83. f.Bool("upgrade", false, "upgrade database to the current version")
  84. f.Bool("version", false, "current version of the build")
  85. f.Bool("new-config", false, "generate sample config file")
  86. f.String("static-dir", "", "(optional) path to directory with static files")
  87. f.String("i18n-dir", "", "(optional) path to directory with i18n language files")
  88. f.Bool("yes", false, "assume 'yes' to prompts during --install/upgrade")
  89. if err := f.Parse(os.Args[1:]); err != nil {
  90. lo.Fatalf("error loading flags: %v", err)
  91. }
  92. if err := ko.Load(posflag.Provider(f, ".", ko), nil); err != nil {
  93. lo.Fatalf("error loading config: %v", err)
  94. }
  95. }
  96. // initConfigFiles loads the given config files into the koanf instance.
  97. func initConfigFiles(files []string, ko *koanf.Koanf) {
  98. for _, f := range files {
  99. lo.Printf("reading config: %s", f)
  100. if err := ko.Load(file.Provider(f), toml.Parser()); err != nil {
  101. if os.IsNotExist(err) {
  102. lo.Fatal("config file not found. If there isn't one yet, run --new-config to generate one.")
  103. }
  104. lo.Fatalf("error loadng config from file: %v.", err)
  105. }
  106. }
  107. }
  108. // initFileSystem initializes the stuffbin FileSystem to provide
  109. // access to bunded static assets to the app.
  110. func initFS(appDir, frontendDir, staticDir, i18nDir string) stuffbin.FileSystem {
  111. var (
  112. // stuffbin real_path:virtual_alias paths to map local assets on disk
  113. // when there an embedded filestystem is not found.
  114. // These paths are joined with appDir.
  115. appFiles = []string{
  116. "./config.toml.sample:config.toml.sample",
  117. "./queries.sql:queries.sql",
  118. "./schema.sql:schema.sql",
  119. }
  120. frontendFiles = []string{
  121. // Admin frontend's static assets accessible at /admin/* during runtime.
  122. // These paths are sourced from frontendDir.
  123. "./:/admin",
  124. }
  125. staticFiles = []string{
  126. // These paths are joined with staticDir.
  127. "./email-templates:static/email-templates",
  128. "./public:/public",
  129. }
  130. i18nFiles = []string{
  131. // These paths are joined with i18nDir.
  132. "./:/i18n",
  133. }
  134. )
  135. // Get the executable's path.
  136. path, err := os.Executable()
  137. if err != nil {
  138. lo.Fatalf("error getting executable path: %v", err)
  139. }
  140. // Load embedded files in the executable.
  141. hasEmbed := true
  142. fs, err := stuffbin.UnStuff(path)
  143. if err != nil {
  144. hasEmbed = false
  145. // Running in local mode. Load local assets into
  146. // the in-memory stuffbin.FileSystem.
  147. lo.Printf("unable to initialize embedded filesystem (%v). Using local filesystem", err)
  148. fs, err = stuffbin.NewLocalFS("/")
  149. if err != nil {
  150. lo.Fatalf("failed to initialize local file for assets: %v", err)
  151. }
  152. }
  153. // If the embed failed, load app and frontend files from the compile-time paths.
  154. files := []string{}
  155. if !hasEmbed {
  156. files = append(files, joinFSPaths(appDir, appFiles)...)
  157. files = append(files, joinFSPaths(frontendDir, frontendFiles)...)
  158. }
  159. // Irrespective of the embeds, if there are user specified static or i18n paths,
  160. // load files from there and override default files (embedded or picked up from CWD).
  161. if !hasEmbed || i18nDir != "" {
  162. if i18nDir == "" {
  163. // Default dir in cwd.
  164. i18nDir = "i18n"
  165. }
  166. lo.Printf("will load i18n files from: %v", i18nDir)
  167. files = append(files, joinFSPaths(i18nDir, i18nFiles)...)
  168. }
  169. if !hasEmbed || staticDir != "" {
  170. if staticDir == "" {
  171. // Default dir in cwd.
  172. staticDir = "static"
  173. }
  174. lo.Printf("will load static files from: %v", staticDir)
  175. files = append(files, joinFSPaths(staticDir, staticFiles)...)
  176. }
  177. // No additional files to load.
  178. if len(files) == 0 {
  179. return fs
  180. }
  181. // Load files from disk and overlay into the FS.
  182. fStatic, err := stuffbin.NewLocalFS("/", files...)
  183. if err != nil {
  184. lo.Fatalf("failed reading static files from disk: '%s': %v", staticDir, err)
  185. }
  186. if err := fs.Merge(fStatic); err != nil {
  187. lo.Fatalf("error merging static files: '%s': %v", staticDir, err)
  188. }
  189. return fs
  190. }
  191. // initDB initializes the main DB connection pool and parse and loads the app's
  192. // SQL queries into a prepared query map.
  193. func initDB() *sqlx.DB {
  194. var dbCfg dbConf
  195. if err := ko.Unmarshal("db", &dbCfg); err != nil {
  196. lo.Fatalf("error loading db config: %v", err)
  197. }
  198. lo.Printf("connecting to db: %s:%d/%s", dbCfg.Host, dbCfg.Port, dbCfg.DBName)
  199. db, err := connectDB(dbCfg)
  200. if err != nil {
  201. lo.Fatalf("error connecting to DB: %v", err)
  202. }
  203. return db
  204. }
  205. // initQueries loads named SQL queries from the queries file and optionally
  206. // prepares them.
  207. func initQueries(sqlFile string, db *sqlx.DB, fs stuffbin.FileSystem, prepareQueries bool) (goyesql.Queries, *Queries) {
  208. // Load SQL queries.
  209. qB, err := fs.Read(sqlFile)
  210. if err != nil {
  211. lo.Fatalf("error reading SQL file %s: %v", sqlFile, err)
  212. }
  213. qMap, err := goyesql.ParseBytes(qB)
  214. if err != nil {
  215. lo.Fatalf("error parsing SQL queries: %v", err)
  216. }
  217. if !prepareQueries {
  218. return qMap, nil
  219. }
  220. // Prepare queries.
  221. var q Queries
  222. if err := goyesqlx.ScanToStruct(&q, qMap, db.Unsafe()); err != nil {
  223. lo.Fatalf("error preparing SQL queries: %v", err)
  224. }
  225. return qMap, &q
  226. }
  227. // initSettings loads settings from the DB.
  228. func initSettings(q *sqlx.Stmt) {
  229. var s types.JSONText
  230. if err := q.Get(&s); err != nil {
  231. lo.Fatalf("error reading settings from DB: %s", pqErrMsg(err))
  232. }
  233. // Setting keys are dot separated, eg: app.favicon_url. Unflatten them into
  234. // nested maps {app: {favicon_url}}.
  235. var out map[string]interface{}
  236. if err := json.Unmarshal(s, &out); err != nil {
  237. lo.Fatalf("error unmarshalling settings from DB: %v", err)
  238. }
  239. if err := ko.Load(confmap.Provider(out, "."), nil); err != nil {
  240. lo.Fatalf("error parsing settings from DB: %v", err)
  241. }
  242. }
  243. func initConstants() *constants {
  244. // Read constants.
  245. var c constants
  246. if err := ko.Unmarshal("app", &c); err != nil {
  247. lo.Fatalf("error loading app config: %v", err)
  248. }
  249. if err := ko.Unmarshal("privacy", &c.Privacy); err != nil {
  250. lo.Fatalf("error loading app config: %v", err)
  251. }
  252. c.RootURL = strings.TrimRight(c.RootURL, "/")
  253. c.Lang = ko.String("app.lang")
  254. c.Privacy.Exportable = maps.StringSliceToLookupMap(ko.Strings("privacy.exportable"))
  255. c.MediaProvider = ko.String("upload.provider")
  256. // Static URLS.
  257. // url.com/subscription/{campaign_uuid}/{subscriber_uuid}
  258. c.UnsubURL = fmt.Sprintf("%s/subscription/%%s/%%s", c.RootURL)
  259. // url.com/subscription/optin/{subscriber_uuid}
  260. c.OptinURL = fmt.Sprintf("%s/subscription/optin/%%s?%%s", c.RootURL)
  261. // url.com/link/{campaign_uuid}/{subscriber_uuid}/{link_uuid}
  262. c.LinkTrackURL = fmt.Sprintf("%s/link/%%s/%%s/%%s", c.RootURL)
  263. // url.com/link/{campaign_uuid}/{subscriber_uuid}
  264. c.MessageURL = fmt.Sprintf("%s/campaign/%%s/%%s", c.RootURL)
  265. // url.com/campaign/{campaign_uuid}/{subscriber_uuid}/px.png
  266. c.ViewTrackURL = fmt.Sprintf("%s/campaign/%%s/%%s/px.png", c.RootURL)
  267. c.BounceWebhooksEnabled = ko.Bool("bounce.webhooks_enabled")
  268. c.BounceSESEnabled = ko.Bool("bounce.ses_enabled")
  269. c.BounceSendgridEnabled = ko.Bool("bounce.sendgrid_enabled")
  270. return &c
  271. }
  272. // initI18n initializes a new i18n instance with the selected language map
  273. // loaded from the filesystem. English is a loaded first as the default map
  274. // and then the selected language is loaded on top of it so that if there are
  275. // missing translations in it, the default English translations show up.
  276. func initI18n(lang string, fs stuffbin.FileSystem) *i18n.I18n {
  277. i, ok, err := getI18nLang(lang, fs)
  278. if err != nil {
  279. if ok {
  280. lo.Println(err)
  281. } else {
  282. lo.Fatal(err)
  283. }
  284. }
  285. return i
  286. }
  287. // initCampaignManager initializes the campaign manager.
  288. func initCampaignManager(q *Queries, cs *constants, app *App) *manager.Manager {
  289. campNotifCB := func(subject string, data interface{}) error {
  290. return app.sendNotification(cs.NotifyEmails, subject, notifTplCampaign, data)
  291. }
  292. if ko.Int("app.concurrency") < 1 {
  293. lo.Fatal("app.concurrency should be at least 1")
  294. }
  295. if ko.Int("app.message_rate") < 1 {
  296. lo.Fatal("app.message_rate should be at least 1")
  297. }
  298. return manager.New(manager.Config{
  299. BatchSize: ko.Int("app.batch_size"),
  300. Concurrency: ko.Int("app.concurrency"),
  301. MessageRate: ko.Int("app.message_rate"),
  302. MaxSendErrors: ko.Int("app.max_send_errors"),
  303. FromEmail: cs.FromEmail,
  304. IndividualTracking: ko.Bool("privacy.individual_tracking"),
  305. UnsubURL: cs.UnsubURL,
  306. OptinURL: cs.OptinURL,
  307. LinkTrackURL: cs.LinkTrackURL,
  308. ViewTrackURL: cs.ViewTrackURL,
  309. MessageURL: cs.MessageURL,
  310. UnsubHeader: ko.Bool("privacy.unsubscribe_header"),
  311. SlidingWindow: ko.Bool("app.message_sliding_window"),
  312. SlidingWindowDuration: ko.Duration("app.message_sliding_window_duration"),
  313. SlidingWindowRate: ko.Int("app.message_sliding_window_rate"),
  314. }, newManagerStore(q), campNotifCB, app.i18n, lo)
  315. }
  316. // initImporter initializes the bulk subscriber importer.
  317. func initImporter(q *Queries, db *sqlx.DB, app *App) *subimporter.Importer {
  318. return subimporter.New(
  319. subimporter.Options{
  320. UpsertStmt: q.UpsertSubscriber.Stmt,
  321. BlocklistStmt: q.UpsertBlocklistSubscriber.Stmt,
  322. UpdateListDateStmt: q.UpdateListsDate.Stmt,
  323. NotifCB: func(subject string, data interface{}) error {
  324. app.sendNotification(app.constants.NotifyEmails, subject, notifTplImport, data)
  325. return nil
  326. },
  327. }, db.DB)
  328. }
  329. // initSMTPMessenger initializes the SMTP messenger.
  330. func initSMTPMessenger(m *manager.Manager) messenger.Messenger {
  331. var (
  332. mapKeys = ko.MapKeys("smtp")
  333. servers = make([]email.Server, 0, len(mapKeys))
  334. )
  335. items := ko.Slices("smtp")
  336. if len(items) == 0 {
  337. lo.Fatalf("no SMTP servers found in config")
  338. }
  339. // Load the config for multipme SMTP servers.
  340. for _, item := range items {
  341. if !item.Bool("enabled") {
  342. continue
  343. }
  344. // Read the SMTP config.
  345. var s email.Server
  346. if err := item.UnmarshalWithConf("", &s, koanf.UnmarshalConf{Tag: "json"}); err != nil {
  347. lo.Fatalf("error reading SMTP config: %v", err)
  348. }
  349. servers = append(servers, s)
  350. lo.Printf("loaded email (SMTP) messenger: %s@%s",
  351. item.String("username"), item.String("host"))
  352. }
  353. if len(servers) == 0 {
  354. lo.Fatalf("no SMTP servers enabled in settings")
  355. }
  356. // Initialize the e-mail messenger with multiple SMTP servers.
  357. msgr, err := email.New(servers...)
  358. if err != nil {
  359. lo.Fatalf("error loading e-mail messenger: %v", err)
  360. }
  361. return msgr
  362. }
  363. // initPostbackMessengers initializes and returns all the enabled
  364. // HTTP postback messenger backends.
  365. func initPostbackMessengers(m *manager.Manager) []messenger.Messenger {
  366. items := ko.Slices("messengers")
  367. if len(items) == 0 {
  368. return nil
  369. }
  370. var out []messenger.Messenger
  371. for _, item := range items {
  372. if !item.Bool("enabled") {
  373. continue
  374. }
  375. // Read the Postback server config.
  376. var (
  377. name = item.String("name")
  378. o postback.Options
  379. )
  380. if err := item.UnmarshalWithConf("", &o, koanf.UnmarshalConf{Tag: "json"}); err != nil {
  381. lo.Fatalf("error reading Postback config: %v", err)
  382. }
  383. // Initialize the Messenger.
  384. p, err := postback.New(o)
  385. if err != nil {
  386. lo.Fatalf("error initializing Postback messenger %s: %v", name, err)
  387. }
  388. out = append(out, p)
  389. lo.Printf("loaded Postback messenger: %s", name)
  390. }
  391. return out
  392. }
  393. // initMediaStore initializes Upload manager with a custom backend.
  394. func initMediaStore() media.Store {
  395. switch provider := ko.String("upload.provider"); provider {
  396. case "s3":
  397. var o s3.Opt
  398. ko.Unmarshal("upload.s3", &o)
  399. up, err := s3.NewS3Store(o)
  400. if err != nil {
  401. lo.Fatalf("error initializing s3 upload provider %s", err)
  402. }
  403. lo.Println("media upload provider: s3")
  404. return up
  405. case "filesystem":
  406. var o filesystem.Opts
  407. ko.Unmarshal("upload.filesystem", &o)
  408. o.RootURL = ko.String("app.root_url")
  409. o.UploadPath = filepath.Clean(o.UploadPath)
  410. o.UploadURI = filepath.Clean(o.UploadURI)
  411. up, err := filesystem.NewDiskStore(o)
  412. if err != nil {
  413. lo.Fatalf("error initializing filesystem upload provider %s", err)
  414. }
  415. lo.Println("media upload provider: filesystem")
  416. return up
  417. default:
  418. lo.Fatalf("unknown provider. select filesystem or s3")
  419. }
  420. return nil
  421. }
  422. // initNotifTemplates compiles and returns e-mail notification templates that are
  423. // used for sending ad-hoc notifications to admins and subscribers.
  424. func initNotifTemplates(path string, fs stuffbin.FileSystem, i *i18n.I18n, cs *constants) *template.Template {
  425. // Register utility functions that the e-mail templates can use.
  426. funcs := template.FuncMap{
  427. "RootURL": func() string {
  428. return cs.RootURL
  429. },
  430. "LogoURL": func() string {
  431. return cs.LogoURL
  432. },
  433. "L": func() *i18n.I18n {
  434. return i
  435. },
  436. }
  437. tpl, err := stuffbin.ParseTemplatesGlob(funcs, fs, "/static/email-templates/*.html")
  438. if err != nil {
  439. lo.Fatalf("error parsing e-mail notif templates: %v", err)
  440. }
  441. return tpl
  442. }
  443. // initBounceManager initializes the bounce manager that scans mailboxes and listens to webhooks
  444. // for incoming bounce events.
  445. func initBounceManager(app *App) *bounce.Manager {
  446. opt := bounce.Opt{
  447. BounceCount: ko.MustInt("bounce.count"),
  448. BounceAction: ko.MustString("bounce.action"),
  449. WebhooksEnabled: ko.Bool("bounce.webhooks_enabled"),
  450. SESEnabled: ko.Bool("bounce.ses_enabled"),
  451. SendgridEnabled: ko.Bool("bounce.sendgrid_enabled"),
  452. SendgridKey: ko.String("bounce.sendgrid_key"),
  453. }
  454. // For now, only one mailbox is supported.
  455. for _, b := range ko.Slices("bounce.mailboxes") {
  456. if !b.Bool("enabled") {
  457. continue
  458. }
  459. var boxOpt mailbox.Opt
  460. if err := b.UnmarshalWithConf("", &boxOpt, koanf.UnmarshalConf{Tag: "json"}); err != nil {
  461. lo.Fatalf("error reading bounce mailbox config: %v", err)
  462. }
  463. opt.MailboxType = b.String("type")
  464. opt.MailboxEnabled = true
  465. opt.Mailbox = boxOpt
  466. break
  467. }
  468. b, err := bounce.New(opt, &bounce.Queries{
  469. RecordQuery: app.queries.RecordBounce,
  470. }, app.log)
  471. if err != nil {
  472. lo.Fatalf("error initializing bounce manager: %v", err)
  473. }
  474. return b
  475. }
  476. // initHTTPServer sets up and runs the app's main HTTP server and blocks forever.
  477. func initHTTPServer(app *App) *echo.Echo {
  478. // Initialize the HTTP server.
  479. var srv = echo.New()
  480. srv.HideBanner = true
  481. // Register app (*App) to be injected into all HTTP handlers.
  482. srv.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
  483. return func(c echo.Context) error {
  484. c.Set("app", app)
  485. return next(c)
  486. }
  487. })
  488. // Parse and load user facing templates.
  489. tpl, err := stuffbin.ParseTemplatesGlob(template.FuncMap{
  490. "L": func() *i18n.I18n {
  491. return app.i18n
  492. }}, app.fs, "/public/templates/*.html")
  493. if err != nil {
  494. lo.Fatalf("error parsing public templates: %v", err)
  495. }
  496. srv.Renderer = &tplRenderer{
  497. templates: tpl,
  498. RootURL: app.constants.RootURL,
  499. LogoURL: app.constants.LogoURL,
  500. FaviconURL: app.constants.FaviconURL}
  501. // Initialize the static file server.
  502. fSrv := app.fs.FileServer()
  503. // Public (subscriber) facing static files.
  504. srv.GET("/public/*", echo.WrapHandler(fSrv))
  505. // Admin (frontend) facing static files.
  506. srv.GET("/admin/static/*", echo.WrapHandler(fSrv))
  507. // Public (subscriber) facing media upload files.
  508. if ko.String("upload.provider") == "filesystem" {
  509. srv.Static(ko.String("upload.filesystem.upload_uri"),
  510. ko.String("upload.filesystem.upload_path"))
  511. }
  512. // Register all HTTP handlers.
  513. initHTTPHandlers(srv, app)
  514. // Start the server.
  515. go func() {
  516. if err := srv.Start(ko.String("app.address")); err != nil {
  517. if strings.Contains(err.Error(), "Server closed") {
  518. lo.Println("HTTP server shut down")
  519. } else {
  520. lo.Fatalf("error starting HTTP server: %v", err)
  521. }
  522. }
  523. }()
  524. return srv
  525. }
  526. func awaitReload(sigChan chan os.Signal, closerWait chan bool, closer func()) chan bool {
  527. // The blocking signal handler that main() waits on.
  528. out := make(chan bool)
  529. // Respawn a new process and exit the running one.
  530. respawn := func() {
  531. if err := syscall.Exec(os.Args[0], os.Args, os.Environ()); err != nil {
  532. lo.Fatalf("error spawning process: %v", err)
  533. }
  534. os.Exit(0)
  535. }
  536. // Listen for reload signal.
  537. go func() {
  538. for range sigChan {
  539. lo.Println("reloading on signal ...")
  540. go closer()
  541. select {
  542. case <-closerWait:
  543. // Wait for the closer to finish.
  544. respawn()
  545. case <-time.After(time.Second * 3):
  546. // Or timeout and force close.
  547. respawn()
  548. }
  549. }
  550. }()
  551. return out
  552. }
  553. func joinFSPaths(root string, paths []string) []string {
  554. out := make([]string, 0, len(paths))
  555. for _, p := range paths {
  556. // real_path:stuffbin_alias
  557. f := strings.Split(p, ":")
  558. out = append(out, path.Join(root, f[0])+":"+f[1])
  559. }
  560. return out
  561. }