caddy/caddy.go

253 lines
6.1 KiB
Go
Raw Normal View History

2019-03-27 05:45:51 +08:00
package caddy2
import (
"encoding/json"
"fmt"
2019-03-27 09:42:52 +08:00
"log"
2019-03-27 05:45:51 +08:00
"strings"
2019-03-27 09:42:52 +08:00
"sync"
"sync/atomic"
2019-03-27 05:45:51 +08:00
"time"
"github.com/mholt/certmagic"
2019-03-27 05:45:51 +08:00
)
// Run runs Caddy with the given config.
func Run(cfg *Config) error {
// allow only one call to Start at a time,
// since various calls to LoadModule()
// access shared map moduleInstances
startMu.Lock()
defer startMu.Unlock()
// because we will need to roll back any state
// modifications if this function errors, we
// keep a single error value and scope all
// sub-operations to their own functions to
// ensure this error value does not get
// overridden or missed when it should have
// been set by a short assignment
var err error
// prepare the new config for use
cfg.apps = make(map[string]App)
cfg.moduleStates = make(map[string]interface{})
// reset the shared moduleInstances map; but
// keep a temporary reference to the current
// one so we can transfer over any necessary
// state to the new modules or to roll back
// if necessary
oldModuleInstances := moduleInstances
defer func() {
if err != nil {
moduleInstances = oldModuleInstances
}
}()
moduleInstances = make(map[string][]interface{})
2019-03-27 05:45:51 +08:00
// set up storage and make it CertMagic's default storage, too
err = func() error {
if cfg.StorageRaw != nil {
val, err := LoadModuleInline("system", "caddy.storage", cfg.StorageRaw)
if err != nil {
return fmt.Errorf("loading storage module: %v", err)
}
stor, err := val.(StorageConverter).CertMagicStorage()
if err != nil {
return fmt.Errorf("creating storage value: %v", err)
}
cfg.storage = stor
cfg.StorageRaw = nil // allow GC to deallocate - TODO: Does this help?
2019-03-27 05:45:51 +08:00
}
if cfg.storage == nil {
cfg.storage = &certmagic.FileStorage{Path: dataDir()}
2019-03-27 05:45:51 +08:00
}
certmagic.Default.Storage = cfg.storage
return nil
}()
if err != nil {
return err
2019-03-27 05:45:51 +08:00
}
// Load, Provision, Validate
err = func() error {
for modName, rawMsg := range cfg.AppsRaw {
val, err := LoadModule(modName, rawMsg)
2019-03-27 09:42:52 +08:00
if err != nil {
return fmt.Errorf("loading app module '%s': %v", modName, err)
2019-03-27 09:42:52 +08:00
}
cfg.apps[modName] = val.(App)
2019-03-27 09:42:52 +08:00
}
return nil
}()
if err != nil {
return err
2019-03-27 09:42:52 +08:00
}
// swap old config with the new one, and
// roll back this change if anything fails
currentCfgMu.Lock()
oldCfg := currentCfg
currentCfg = cfg
2019-03-27 09:42:52 +08:00
currentCfgMu.Unlock()
defer func() {
if err != nil {
currentCfgMu.Lock()
currentCfg = oldCfg
currentCfgMu.Unlock()
}
}()
// Start
err = func() error {
h := Handle{cfg}
for name, a := range cfg.apps {
err := a.Start(h)
if err != nil {
for otherAppName, otherApp := range cfg.apps {
err := otherApp.Stop()
if err != nil {
log.Printf("aborting app %s: %v", otherAppName, err)
}
}
return fmt.Errorf("%s app module: start: %v", name, err)
}
}
return nil
}()
if err != nil {
return err
}
// Stop
if oldCfg != nil {
for name, a := range oldCfg.apps {
err := a.Stop()
if err != nil {
log.Printf("[ERROR] stop %s: %v", name, err)
}
}
}
// shut down listeners that are no longer being used
err = func() error {
listenersMu.Lock()
for key, info := range listeners {
if atomic.LoadInt32(&info.usage) == 0 {
err := info.ln.Close()
if err != nil {
log.Printf("[ERROR] closing listener %s: %v", info.ln.Addr(), err)
continue
}
delete(listeners, key)
}
}
listenersMu.Unlock()
return nil
}()
if err != nil {
return err
}
2019-03-27 05:45:51 +08:00
return nil
}
// App is a thing that Caddy runs.
type App interface {
Start(Handle) error
Stop() error
2019-03-27 05:45:51 +08:00
}
// Config represents a Caddy configuration.
type Config struct {
StorageRaw json.RawMessage `json:"storage"`
storage certmagic.Storage
2019-03-27 05:45:51 +08:00
TestVal string `json:"testval"`
AppsRaw map[string]json.RawMessage `json:"apps"`
// apps stores the decoded Apps values,
// keyed by module name.
apps map[string]App
// moduleStates stores the optional "global" state
// values of every module used by this configuration,
// keyed by module name.
moduleStates map[string]interface{}
2019-03-27 05:45:51 +08:00
}
// Handle allows app modules to access
// the top-level Config in a controlled
// manner without needing to rely on
// global state.
type Handle struct {
current *Config
}
// App returns the configured app named name. If no app with
// that name is currently configured, a new empty one will be
// instantiated. (The app module must still be registered.)
func (h Handle) App(name string) (interface{}, error) {
if app, ok := h.current.apps[name]; ok {
return app, nil
}
modVal, err := LoadModule(name, nil)
if err != nil {
return nil, fmt.Errorf("instantiating new module %s: %v", name, err)
}
h.current.apps[name] = modVal.(App)
return modVal, nil
}
// GetStorage returns the configured Caddy storage implementation.
// If no storage implementation is explicitly configured, the
// default one is returned instead, as long as there is a current
// configuration loaded.
func GetStorage() certmagic.Storage {
currentCfgMu.RLock()
defer currentCfgMu.RUnlock()
if currentCfg == nil {
return nil
}
return currentCfg.storage
}
2019-03-27 05:45:51 +08:00
// Duration is a JSON-string-unmarshable duration type.
type Duration time.Duration
// UnmarshalJSON satisfies json.Unmarshaler.
func (d *Duration) UnmarshalJSON(b []byte) error {
2019-03-27 05:45:51 +08:00
dd, err := time.ParseDuration(strings.Trim(string(b), `"`))
if err != nil {
return err
}
2019-03-27 05:45:51 +08:00
cd := Duration(dd)
d = &cd
return nil
2019-03-27 05:45:51 +08:00
}
// CtxKey is a value type for use with context.WithValue.
type CtxKey string
// currentCfg is the currently-loaded configuration.
var (
currentCfg *Config
currentCfgMu sync.RWMutex
)
// moduleInstances stores the individual instantiated
// values of modules, keyed by module name. The list
// of instances of each module get passed into the
// respective module's OnLoad callback, so they can
// set up any global state and/or make sure their
// configuration, when viewed as a whole, is valid.
// Since this list is shared, only one Start() routine
// must be allowed to happen at any given time.
var moduleInstances = make(map[string][]interface{})
// startMu ensures that only one Start() happens at a time.
// This is important since moduleInstances is shared state.
var startMu sync.Mutex