plugins.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. // Copyright 2015 Light Code Labs, LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package caddy
  15. import (
  16. "fmt"
  17. "log"
  18. "net"
  19. "sort"
  20. "sync"
  21. "github.com/mholt/caddy/caddyfile"
  22. )
  23. // These are all the registered plugins.
  24. var (
  25. // serverTypes is a map of registered server types.
  26. serverTypes = make(map[string]ServerType)
  27. // plugins is a map of server type to map of plugin name to
  28. // Plugin. These are the "general" plugins that may or may
  29. // not be associated with a specific server type. If it's
  30. // applicable to multiple server types or the server type is
  31. // irrelevant, the key is empty string (""). But all plugins
  32. // must have a name.
  33. plugins = make(map[string]map[string]Plugin)
  34. // eventHooks is a map of hook name to Hook. All hooks plugins
  35. // must have a name.
  36. eventHooks = sync.Map{}
  37. // parsingCallbacks maps server type to map of directive
  38. // to list of callback functions. These aren't really
  39. // plugins on their own, but are often registered from
  40. // plugins.
  41. parsingCallbacks = make(map[string]map[string][]ParsingCallback)
  42. // caddyfileLoaders is the list of all Caddyfile loaders
  43. // in registration order.
  44. caddyfileLoaders []caddyfileLoader
  45. )
  46. // DescribePlugins returns a string describing the registered plugins.
  47. func DescribePlugins() string {
  48. str := "Server types:\n"
  49. for name := range serverTypes {
  50. str += " " + name + "\n"
  51. }
  52. // List the loaders in registration order
  53. str += "\nCaddyfile loaders:\n"
  54. for _, loader := range caddyfileLoaders {
  55. str += " " + loader.name + "\n"
  56. }
  57. if defaultCaddyfileLoader.name != "" {
  58. str += " " + defaultCaddyfileLoader.name + "\n"
  59. }
  60. // List the event hook plugins
  61. hooks := ""
  62. eventHooks.Range(func(k, _ interface{}) bool {
  63. hooks += " hook." + k.(string) + "\n"
  64. return true
  65. })
  66. if hooks != "" {
  67. str += "\nEvent hook plugins:\n"
  68. str += hooks
  69. }
  70. // Let's alphabetize the rest of these...
  71. var others []string
  72. for stype, stypePlugins := range plugins {
  73. for name := range stypePlugins {
  74. var s string
  75. if stype != "" {
  76. s = stype + "."
  77. }
  78. s += name
  79. others = append(others, s)
  80. }
  81. }
  82. sort.Strings(others)
  83. str += "\nOther plugins:\n"
  84. for _, name := range others {
  85. str += " " + name + "\n"
  86. }
  87. return str
  88. }
  89. // ValidDirectives returns the list of all directives that are
  90. // recognized for the server type serverType. However, not all
  91. // directives may be installed. This makes it possible to give
  92. // more helpful error messages, like "did you mean ..." or
  93. // "maybe you need to plug in ...".
  94. func ValidDirectives(serverType string) []string {
  95. stype, err := getServerType(serverType)
  96. if err != nil {
  97. return nil
  98. }
  99. return stype.Directives()
  100. }
  101. // ServerListener pairs a server to its listener and/or packetconn.
  102. type ServerListener struct {
  103. server Server
  104. listener net.Listener
  105. packet net.PacketConn
  106. }
  107. // LocalAddr returns the local network address of the packetconn. It returns
  108. // nil when it is not set.
  109. func (s ServerListener) LocalAddr() net.Addr {
  110. if s.packet == nil {
  111. return nil
  112. }
  113. return s.packet.LocalAddr()
  114. }
  115. // Addr returns the listener's network address. It returns nil when it is
  116. // not set.
  117. func (s ServerListener) Addr() net.Addr {
  118. if s.listener == nil {
  119. return nil
  120. }
  121. return s.listener.Addr()
  122. }
  123. // Context is a type which carries a server type through
  124. // the load and setup phase; it maintains the state
  125. // between loading the Caddyfile, then executing its
  126. // directives, then making the servers for Caddy to
  127. // manage. Typically, such state involves configuration
  128. // structs, etc.
  129. type Context interface {
  130. // Called after the Caddyfile is parsed into server
  131. // blocks but before the directives are executed,
  132. // this method gives you an opportunity to inspect
  133. // the server blocks and prepare for the execution
  134. // of directives. Return the server blocks (which
  135. // you may modify, if desired) and an error, if any.
  136. // The first argument is the name or path to the
  137. // configuration file (Caddyfile).
  138. //
  139. // This function can be a no-op and simply return its
  140. // input if there is nothing to do here.
  141. InspectServerBlocks(string, []caddyfile.ServerBlock) ([]caddyfile.ServerBlock, error)
  142. // This is what Caddy calls to make server instances.
  143. // By this time, all directives have been executed and,
  144. // presumably, the context has enough state to produce
  145. // server instances for Caddy to start.
  146. MakeServers() ([]Server, error)
  147. }
  148. // RegisterServerType registers a server type srv by its
  149. // name, typeName.
  150. func RegisterServerType(typeName string, srv ServerType) {
  151. if _, ok := serverTypes[typeName]; ok {
  152. panic("server type already registered")
  153. }
  154. serverTypes[typeName] = srv
  155. }
  156. // ServerType contains information about a server type.
  157. type ServerType struct {
  158. // Function that returns the list of directives, in
  159. // execution order, that are valid for this server
  160. // type. Directives should be one word if possible
  161. // and lower-cased.
  162. Directives func() []string
  163. // DefaultInput returns a default config input if none
  164. // is otherwise loaded. This is optional, but highly
  165. // recommended, otherwise a blank Caddyfile will be
  166. // used.
  167. DefaultInput func() Input
  168. // The function that produces a new server type context.
  169. // This will be called when a new Caddyfile is being
  170. // loaded, parsed, and executed independently of any
  171. // startup phases before this one. It's a way to keep
  172. // each set of server instances separate and to reduce
  173. // the amount of global state you need.
  174. NewContext func(inst *Instance) Context
  175. }
  176. // Plugin is a type which holds information about a plugin.
  177. type Plugin struct {
  178. // ServerType is the type of server this plugin is for.
  179. // Can be empty if not applicable, or if the plugin
  180. // can associate with any server type.
  181. ServerType string
  182. // Action is the plugin's setup function, if associated
  183. // with a directive in the Caddyfile.
  184. Action SetupFunc
  185. }
  186. // RegisterPlugin plugs in plugin. All plugins should register
  187. // themselves, even if they do not perform an action associated
  188. // with a directive. It is important for the process to know
  189. // which plugins are available.
  190. //
  191. // The plugin MUST have a name: lower case and one word.
  192. // If this plugin has an action, it must be the name of
  193. // the directive that invokes it. A name is always required
  194. // and must be unique for the server type.
  195. func RegisterPlugin(name string, plugin Plugin) {
  196. if name == "" {
  197. panic("plugin must have a name")
  198. }
  199. if _, ok := plugins[plugin.ServerType]; !ok {
  200. plugins[plugin.ServerType] = make(map[string]Plugin)
  201. }
  202. if _, dup := plugins[plugin.ServerType][name]; dup {
  203. panic("plugin named " + name + " already registered for server type " + plugin.ServerType)
  204. }
  205. plugins[plugin.ServerType][name] = plugin
  206. }
  207. // EventName represents the name of an event used with event hooks.
  208. type EventName string
  209. // Define names for the various events
  210. const (
  211. StartupEvent EventName = "startup"
  212. ShutdownEvent EventName = "shutdown"
  213. CertRenewEvent EventName = "certrenew"
  214. InstanceStartupEvent EventName = "instancestartup"
  215. )
  216. // EventHook is a type which holds information about a startup hook plugin.
  217. type EventHook func(eventType EventName, eventInfo interface{}) error
  218. // RegisterEventHook plugs in hook. All the hooks should register themselves
  219. // and they must have a name.
  220. func RegisterEventHook(name string, hook EventHook) {
  221. if name == "" {
  222. panic("event hook must have a name")
  223. }
  224. _, dup := eventHooks.LoadOrStore(name, hook)
  225. if dup {
  226. panic("hook named " + name + " already registered")
  227. }
  228. }
  229. // EmitEvent executes the different hooks passing the EventType as an
  230. // argument. This is a blocking function. Hook developers should
  231. // use 'go' keyword if they don't want to block Caddy.
  232. func EmitEvent(event EventName, info interface{}) {
  233. eventHooks.Range(func(k, v interface{}) bool {
  234. err := v.(EventHook)(event, info)
  235. if err != nil {
  236. log.Printf("error on '%s' hook: %v", k.(string), err)
  237. }
  238. return true
  239. })
  240. }
  241. // ParsingCallback is a function that is called after
  242. // a directive's setup functions have been executed
  243. // for all the server blocks.
  244. type ParsingCallback func(Context) error
  245. // RegisterParsingCallback registers callback to be called after
  246. // executing the directive afterDir for server type serverType.
  247. func RegisterParsingCallback(serverType, afterDir string, callback ParsingCallback) {
  248. if _, ok := parsingCallbacks[serverType]; !ok {
  249. parsingCallbacks[serverType] = make(map[string][]ParsingCallback)
  250. }
  251. parsingCallbacks[serverType][afterDir] = append(parsingCallbacks[serverType][afterDir], callback)
  252. }
  253. // SetupFunc is used to set up a plugin, or in other words,
  254. // execute a directive. It will be called once per key for
  255. // each server block it appears in.
  256. type SetupFunc func(c *Controller) error
  257. // DirectiveAction gets the action for directive dir of
  258. // server type serverType.
  259. func DirectiveAction(serverType, dir string) (SetupFunc, error) {
  260. if stypePlugins, ok := plugins[serverType]; ok {
  261. if plugin, ok := stypePlugins[dir]; ok {
  262. return plugin.Action, nil
  263. }
  264. }
  265. if genericPlugins, ok := plugins[""]; ok {
  266. if plugin, ok := genericPlugins[dir]; ok {
  267. return plugin.Action, nil
  268. }
  269. }
  270. return nil, fmt.Errorf("no action found for directive '%s' with server type '%s' (missing a plugin?)",
  271. dir, serverType)
  272. }
  273. // Loader is a type that can load a Caddyfile.
  274. // It is passed the name of the server type.
  275. // It returns an error only if something went
  276. // wrong, not simply if there is no Caddyfile
  277. // for this loader to load.
  278. //
  279. // A Loader should only load the Caddyfile if
  280. // a certain condition or requirement is met,
  281. // as returning a non-nil Input value along with
  282. // another Loader will result in an error.
  283. // In other words, loading the Caddyfile must
  284. // be deliberate & deterministic, not haphazard.
  285. //
  286. // The exception is the default Caddyfile loader,
  287. // which will be called only if no other Caddyfile
  288. // loaders return a non-nil Input. The default
  289. // loader may always return an Input value.
  290. type Loader interface {
  291. Load(serverType string) (Input, error)
  292. }
  293. // LoaderFunc is a convenience type similar to http.HandlerFunc
  294. // that allows you to use a plain function as a Load() method.
  295. type LoaderFunc func(serverType string) (Input, error)
  296. // Load loads a Caddyfile.
  297. func (lf LoaderFunc) Load(serverType string) (Input, error) {
  298. return lf(serverType)
  299. }
  300. // RegisterCaddyfileLoader registers loader named name.
  301. func RegisterCaddyfileLoader(name string, loader Loader) {
  302. caddyfileLoaders = append(caddyfileLoaders, caddyfileLoader{name: name, loader: loader})
  303. }
  304. // SetDefaultCaddyfileLoader registers loader by name
  305. // as the default Caddyfile loader if no others produce
  306. // a Caddyfile. If another Caddyfile loader has already
  307. // been set as the default, this replaces it.
  308. //
  309. // Do not call RegisterCaddyfileLoader on the same
  310. // loader; that would be redundant.
  311. func SetDefaultCaddyfileLoader(name string, loader Loader) {
  312. defaultCaddyfileLoader = caddyfileLoader{name: name, loader: loader}
  313. }
  314. // loadCaddyfileInput iterates the registered Caddyfile loaders
  315. // and, if needed, calls the default loader, to load a Caddyfile.
  316. // It is an error if any of the loaders return an error or if
  317. // more than one loader returns a Caddyfile.
  318. func loadCaddyfileInput(serverType string) (Input, error) {
  319. var loadedBy string
  320. var caddyfileToUse Input
  321. for _, l := range caddyfileLoaders {
  322. cdyfile, err := l.loader.Load(serverType)
  323. if err != nil {
  324. return nil, fmt.Errorf("loading Caddyfile via %s: %v", l.name, err)
  325. }
  326. if cdyfile != nil {
  327. if caddyfileToUse != nil {
  328. return nil, fmt.Errorf("Caddyfile loaded multiple times; first by %s, then by %s", loadedBy, l.name)
  329. }
  330. loaderUsed = l
  331. caddyfileToUse = cdyfile
  332. loadedBy = l.name
  333. }
  334. }
  335. if caddyfileToUse == nil && defaultCaddyfileLoader.loader != nil {
  336. cdyfile, err := defaultCaddyfileLoader.loader.Load(serverType)
  337. if err != nil {
  338. return nil, err
  339. }
  340. if cdyfile != nil {
  341. loaderUsed = defaultCaddyfileLoader
  342. caddyfileToUse = cdyfile
  343. }
  344. }
  345. return caddyfileToUse, nil
  346. }
  347. // OnProcessExit is a list of functions to run when the process
  348. // exits -- they are ONLY for cleanup and should not block,
  349. // return errors, or do anything fancy. They will be run with
  350. // every signal, even if "shutdown callbacks" are not executed.
  351. // This variable must only be modified in the main goroutine
  352. // from init() functions.
  353. var OnProcessExit []func()
  354. // caddyfileLoader pairs the name of a loader to the loader.
  355. type caddyfileLoader struct {
  356. name string
  357. loader Loader
  358. }
  359. var (
  360. defaultCaddyfileLoader caddyfileLoader // the default loader if all else fail
  361. loaderUsed caddyfileLoader // the loader that was used (relevant for reloads)
  362. )