Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gui: Rework create and run lifecycles. #371

Merged
merged 5 commits into from
Sep 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions internal/gui/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,19 +89,45 @@ type Cache struct {
lastPaymentInfoMtx sync.RWMutex
}

// InitCache initialises and returns a cache for use in the GUI.
func InitCache(work []*pool.AcceptedWork, quotas []*pool.Quota,
hashData map[string][]*pool.HashData, pendingPmts []*pool.Payment,
archivedPmts []*pool.Payment, blockExplorerURL string,
lastPmtHeight uint32, lastPmtPaidOn, lastPmtCreatedOn int64) *Cache {
// initCache initialises and returns a cache for use in the GUI.
func initCache(cfg *Config) (*Cache, error) {
work, err := cfg.FetchMinedWork()
if err != nil {
return nil, err
}

quotas, err := cfg.FetchWorkQuotas()
if err != nil {
return nil, err
}

hashData, err := cfg.FetchHashData()
if err != nil {
return nil, err
}

pendingPmts, err := cfg.FetchPendingPayments()
if err != nil {
return nil, err
}

archivedPmts, err := cfg.FetchArchivedPayments()
if err != nil {
return nil, err
}

lastPmtHeight, lastPmtPaidOn, lastPmtCreatedOn, err := cfg.FetchLastPaymentInfo()
if err != nil {
return nil, err
}

cache := Cache{blockExplorerURL: blockExplorerURL}
cache := Cache{blockExplorerURL: cfg.BlockExplorerURL}
cache.updateMinedWork(work)
cache.updateRewardQuotas(quotas)
cache.updateHashData(hashData)
cache.updatePayments(pendingPmts, archivedPmts)
cache.updateLastPaymentInfo(lastPmtHeight, lastPmtPaidOn, lastPmtCreatedOn)
return &cache
return &cache, nil
}

// min returns the smaller of the two provided integers.
Expand Down
233 changes: 107 additions & 126 deletions internal/gui/gui.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import (
"crypto/tls"
"errors"
"html/template"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"

"golang.org/x/crypto/acme/autocert"
Expand Down Expand Up @@ -93,7 +95,6 @@ type GUI struct {
templates *template.Template
cookieStore *sessions.CookieStore
router *mux.Router
server *http.Server
cache *Cache
websocketServer *WebsocketServer
}
Expand Down Expand Up @@ -121,8 +122,6 @@ type headerData struct {

// route configures the http router of the user interface.
func (ui *GUI) route() {
ui.router = mux.NewRouter()

// Use a separate router without rate limiting (or other restrictions) for
// static assets.
assetsRouter := ui.router.PathPrefix("/assets").Subrouter()
Expand Down Expand Up @@ -179,28 +178,8 @@ func (ui *GUI) renderTemplate(w http.ResponseWriter, name string, data interface
}
}

// NewGUI creates an instance of the user interface.
func NewGUI(cfg *Config) (*GUI, error) {
ui := &GUI{
cfg: cfg,
limiter: pool.NewRateLimiter(),
}

ui.cookieStore = sessions.NewCookieStore(cfg.CSRFSecret)
ui.websocketServer = NewWebsocketServer()

err := ui.loadTemplates()
if err != nil {
return nil, err
}

ui.route()

return ui, nil
}

// loadTemplates initializes the html templates of the pool user interface.
func (ui *GUI) loadTemplates() error {
func loadTemplates(cfg *Config) (*template.Template, error) {
var templates []string
findTemplate := func(path string, f os.FileInfo, err error) error {
// If path doesn't exist, or other error with path, return error so
Expand All @@ -214,137 +193,124 @@ func (ui *GUI) loadTemplates() error {
return nil
}

err := filepath.Walk(ui.cfg.GUIDir, findTemplate)
err := filepath.Walk(cfg.GUIDir, findTemplate)
if err != nil {
return err
return nil, err
}

httpTemplates := template.New("template").Funcs(template.FuncMap{
"upper": strings.ToUpper,
"floatToPercent": floatToPercent,
})

// Since template.Must panics with non-nil error, it is much more
// informative to pass the error to the caller to log it and exit
// gracefully.
httpTemplates, err = httpTemplates.ParseFiles(templates...)
return httpTemplates.ParseFiles(templates...)
}

// NewGUI creates an instance of the user interface.
func NewGUI(cfg *Config) (*GUI, error) {
templates, err := loadTemplates(cfg)
if err != nil {
return err
return nil, err
}

ui.templates = template.Must(httpTemplates, nil)
return nil
cache, err := initCache(cfg)
if err != nil {
return nil, err
}

ui := GUI{
cfg: cfg,
limiter: pool.NewRateLimiter(),
templates: templates,
cookieStore: sessions.NewCookieStore(cfg.CSRFSecret),
router: mux.NewRouter(),
cache: cache,
websocketServer: NewWebsocketServer(),
}
ui.route()
return &ui, nil
}

// Run starts the user interface.
func (ui *GUI) Run(ctx context.Context) {
go func() {
switch {
case ui.cfg.UseLEHTTPS:
certMgr := &autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocert.DirCache("certs"),
HostPolicy: autocert.HostWhitelist(ui.cfg.Domain),
}
// runWebServer starts the web server according per the configuration options
// associated with the GUI instance.
//
// It must be run as a routine.
func (ui *GUI) runWebServer(ctx context.Context) {
// Create base HTTP/S server configuration.
server := http.Server{
// Use the provided context as the parent context for all requests to
// ensure handlers are able to react to both client disconnects as well
// as shutdown via the provided context.
BaseContext: func(l net.Listener) context.Context {
return ctx
},

WriteTimeout: time.Second * 30,
ReadTimeout: time.Second * 30,
IdleTimeout: time.Second * 30,
Addr: ui.cfg.GUIListen,
Handler: ui.router,
}

log.Info("Starting GUI server on port 443 (https)")
ui.server = &http.Server{
WriteTimeout: time.Second * 30,
ReadTimeout: time.Second * 30,
IdleTimeout: time.Second * 30,
Addr: ":https",
Handler: ui.router,
TLSConfig: &tls.Config{
GetCertificate: certMgr.GetCertificate,
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
},
},
}
switch {
case ui.cfg.UseLEHTTPS:
certMgr := &autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocert.DirCache("certs"),
HostPolicy: autocert.HostWhitelist(ui.cfg.Domain),
}

if err := ui.server.ListenAndServeTLS("", ""); err != nil {
server.Addr = ":https"
server.TLSConfig = &tls.Config{
GetCertificate: certMgr.GetCertificate,
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
},
}

go func() {
log.Info("Starting GUI server on port 443 (https)")
if err := server.ListenAndServeTLS("", ""); err != nil {
log.Error(err)
}
case ui.cfg.NoGUITLS:
log.Infof("Starting GUI server on %s (http)", ui.cfg.GUIListen)
ui.server = &http.Server{
WriteTimeout: time.Second * 30,
ReadTimeout: time.Second * 30,
IdleTimeout: time.Second * 30,
Addr: ui.cfg.GUIListen,
Handler: ui.router,
}
}()

if err := ui.server.ListenAndServe(); err != nil &&
case ui.cfg.NoGUITLS:
go func() {
log.Infof("Starting GUI server on %s (http)", ui.cfg.GUIListen)
if err := server.ListenAndServe(); err != nil &&
!errors.Is(err, http.ErrServerClosed) {
log.Error(err)
}
default:
log.Infof("Starting GUI server on %s (https)", ui.cfg.GUIListen)
ui.server = &http.Server{
WriteTimeout: time.Second * 30,
ReadTimeout: time.Second * 30,
IdleTimeout: time.Second * 30,
Addr: ui.cfg.GUIListen,
Handler: ui.router,
}
}()

if err := ui.server.ListenAndServeTLS(ui.cfg.TLSCertFile,
default:
go func() {
log.Infof("Starting GUI server on %s (https)", ui.cfg.GUIListen)
if err := server.ListenAndServeTLS(ui.cfg.TLSCertFile,
ui.cfg.TLSKeyFile); err != nil &&
!errors.Is(err, http.ErrServerClosed) {
log.Error(err)
}
}
}()

// Initialise the cache.
work, err := ui.cfg.FetchMinedWork()
if err != nil {
log.Error(err)
return
}

quotas, err := ui.cfg.FetchWorkQuotas()
if err != nil {
log.Error(err)
return
}

hashData, err := ui.cfg.FetchHashData()
if err != nil {
log.Error(err)
return
}

pendingPayments, err := ui.cfg.FetchPendingPayments()
if err != nil {
log.Error(err)
return
}

archivedPayments, err := ui.cfg.FetchArchivedPayments()
if err != nil {
log.Error(err)
return
}

lastPmtHeight, lastPmtPaidOn, lastPmtCreatedOn, err := ui.cfg.FetchLastPaymentInfo()
if err != nil {
log.Error(err)
return
}()
}

ui.cache = InitCache(work, quotas, hashData, pendingPayments, archivedPayments,
ui.cfg.BlockExplorerURL, lastPmtHeight, lastPmtPaidOn, lastPmtCreatedOn)
// Wait until the context is canceled and gracefully shutdown the server.
<-ctx.Done()
server.Shutdown(ctx)
}

// Use a ticker to periodically update cached data and push updates through
// any established websockets
// updateCacheAndNotifyWebsocketClients periodically updates cached data and
// pushes updates to any established websocket clients.
//
// It must be run as a routine.
func (ui *GUI) updateCacheAndNotifyWebsocketClients(ctx context.Context) {
signalCh := ui.cfg.FetchCacheChannel()
ticker := time.NewTicker(15 * time.Second)
defer ticker.Stop()
Expand Down Expand Up @@ -421,3 +387,18 @@ func (ui *GUI) Run(ctx context.Context) {
}
}
}

// Run starts the user interface.
func (ui *GUI) Run(ctx context.Context) {
var wg sync.WaitGroup
wg.Add(2)
go func() {
ui.runWebServer(ctx)
wg.Done()
}()
go func() {
ui.updateCacheAndNotifyWebsocketClients(ctx)
wg.Done()
}()
wg.Wait()
}
Loading