plugins.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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/coredns/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. pl := ListPlugins()
  49. str := "Server types:\n"
  50. for _, name := range pl["server_types"] {
  51. str += " " + name + "\n"
  52. }
  53. str += "\nCaddyfile loaders:\n"
  54. for _, name := range pl["caddyfile_loaders"] {
  55. str += " " + name + "\n"
  56. }
  57. if len(pl["event_hooks"]) > 0 {
  58. str += "\nEvent hook plugins:\n"
  59. for _, name := range pl["event_hooks"] {
  60. str += " hook." + name + "\n"
  61. }
  62. }
  63. if len(pl["clustering"]) > 0 {
  64. str += "\nClustering plugins:\n"
  65. for _, name := range pl["clustering"] {
  66. str += " " + name + "\n"
  67. }
  68. }
  69. str += "\nOther plugins:\n"
  70. for _, name := range pl["others"] {
  71. str += " " + name + "\n"
  72. }
  73. return str
  74. }
  75. // ListPlugins makes a list of the registered plugins,
  76. // keyed by plugin type.
  77. func ListPlugins() map[string][]string {
  78. p := make(map[string][]string)
  79. // server type plugins
  80. for name := range serverTypes {
  81. p["server_types"] = append(p["server_types"], name)
  82. }
  83. // caddyfile loaders in registration order
  84. for _, loader := range caddyfileLoaders {
  85. p["caddyfile_loaders"] = append(p["caddyfile_loaders"], loader.name)
  86. }
  87. if defaultCaddyfileLoader.name != "" {
  88. p["caddyfile_loaders"] = append(p["caddyfile_loaders"], defaultCaddyfileLoader.name)
  89. }
  90. // List the event hook plugins
  91. eventHooks.Range(func(k, _ interface{}) bool {
  92. p["event_hooks"] = append(p["event_hooks"], k.(string))
  93. return true
  94. })
  95. // alphabetize the rest of the plugins
  96. var others []string
  97. for stype, stypePlugins := range plugins {
  98. for name := range stypePlugins {
  99. var s string
  100. if stype != "" {
  101. s = stype + "."
  102. }
  103. s += name
  104. others = append(others, s)
  105. }
  106. }
  107. sort.Strings(others)
  108. for _, name := range others {
  109. p["others"] = append(p["others"], name)
  110. }
  111. return p
  112. }
  113. // ValidDirectives returns the list of all directives that are
  114. // recognized for the server type serverType. However, not all
  115. // directives may be installed. This makes it possible to give
  116. // more helpful error messages, like "did you mean ..." or
  117. // "maybe you need to plug in ...".
  118. func ValidDirectives(serverType string) []string {
  119. stype, err := getServerType(serverType)
  120. if err != nil {
  121. return nil
  122. }
  123. return stype.Directives()
  124. }
  125. // ServerListener pairs a server to its listener and/or packetconn.
  126. type ServerListener struct {
  127. server Server
  128. listener net.Listener
  129. packet net.PacketConn
  130. }
  131. // LocalAddr returns the local network address of the packetconn. It returns
  132. // nil when it is not set.
  133. func (s ServerListener) LocalAddr() net.Addr {
  134. if s.packet == nil {
  135. return nil
  136. }
  137. return s.packet.LocalAddr()
  138. }
  139. // Addr returns the listener's network address. It returns nil when it is
  140. // not set.
  141. func (s ServerListener) Addr() net.Addr {
  142. if s.listener == nil {
  143. return nil
  144. }
  145. return s.listener.Addr()
  146. }
  147. // Context is a type which carries a server type through
  148. // the load and setup phase; it maintains the state
  149. // between loading the Caddyfile, then executing its
  150. // directives, then making the servers for Caddy to
  151. // manage. Typically, such state involves configuration
  152. // structs, etc.
  153. type Context interface {
  154. // Called after the Caddyfile is parsed into server
  155. // blocks but before the directives are executed,
  156. // this method gives you an opportunity to inspect
  157. // the server blocks and prepare for the execution
  158. // of directives. Return the server blocks (which
  159. // you may modify, if desired) and an error, if any.
  160. // The first argument is the name or path to the
  161. // configuration file (Caddyfile).
  162. //
  163. // This function can be a no-op and simply return its
  164. // input if there is nothing to do here.
  165. InspectServerBlocks(string, []caddyfile.ServerBlock) ([]caddyfile.ServerBlock, error)
  166. // This is what Caddy calls to make server instances.
  167. // By this time, all directives have been executed and,
  168. // presumably, the context has enough state to produce
  169. // server instances for Caddy to start.
  170. MakeServers() ([]Server, error)
  171. }
  172. // RegisterServerType registers a server type srv by its
  173. // name, typeName.
  174. func RegisterServerType(typeName string, srv ServerType) {
  175. if _, ok := serverTypes[typeName]; ok {
  176. panic("server type already registered")
  177. }
  178. serverTypes[typeName] = srv
  179. }
  180. // ServerType contains information about a server type.
  181. type ServerType struct {
  182. // Function that returns the list of directives, in
  183. // execution order, that are valid for this server
  184. // type. Directives should be one word if possible
  185. // and lower-cased.
  186. Directives func() []string
  187. // DefaultInput returns a default config input if none
  188. // is otherwise loaded. This is optional, but highly
  189. // recommended, otherwise a blank Caddyfile will be
  190. // used.
  191. DefaultInput func() Input
  192. // The function that produces a new server type context.
  193. // This will be called when a new Caddyfile is being
  194. // loaded, parsed, and executed independently of any
  195. // startup phases before this one. It's a way to keep
  196. // each set of server instances separate and to reduce
  197. // the amount of global state you need.
  198. NewContext func(inst *Instance) Context
  199. }
  200. // Plugin is a type which holds information about a plugin.
  201. type Plugin struct {
  202. // ServerType is the type of server this plugin is for.
  203. // Can be empty if not applicable, or if the plugin
  204. // can associate with any server type.
  205. ServerType string
  206. // Action is the plugin's setup function, if associated
  207. // with a directive in the Caddyfile.
  208. Action SetupFunc
  209. }
  210. // RegisterPlugin plugs in plugin. All plugins should register
  211. // themselves, even if they do not perform an action associated
  212. // with a directive. It is important for the process to know
  213. // which plugins are available.
  214. //
  215. // The plugin MUST have a name: lower case and one word.
  216. // If this plugin has an action, it must be the name of
  217. // the directive that invokes it. A name is always required
  218. // and must be unique for the server type.
  219. func RegisterPlugin(name string, plugin Plugin) {
  220. if name == "" {
  221. panic("plugin must have a name")
  222. }
  223. if _, ok := plugins[plugin.ServerType]; !ok {
  224. plugins[plugin.ServerType] = make(map[string]Plugin)
  225. }
  226. if _, dup := plugins[plugin.ServerType][name]; dup {
  227. panic("plugin named " + name + " already registered for server type " + plugin.ServerType)
  228. }
  229. plugins[plugin.ServerType][name] = plugin
  230. }
  231. // EventName represents the name of an event used with event hooks.
  232. type EventName string
  233. // Define names for the various events
  234. const (
  235. StartupEvent EventName = "startup"
  236. ShutdownEvent = "shutdown"
  237. CertRenewEvent = "certrenew"
  238. InstanceStartupEvent = "instancestartup"
  239. InstanceRestartEvent = "instancerestart"
  240. )
  241. // EventHook is a type which holds information about a startup hook plugin.
  242. type EventHook func(eventType EventName, eventInfo interface{}) error
  243. // RegisterEventHook plugs in hook. All the hooks should register themselves
  244. // and they must have a name.
  245. func RegisterEventHook(name string, hook EventHook) {
  246. if name == "" {
  247. panic("event hook must have a name")
  248. }
  249. _, dup := eventHooks.LoadOrStore(name, hook)
  250. if dup {
  251. panic("hook named " + name + " already registered")
  252. }
  253. }
  254. // EmitEvent executes the different hooks passing the EventType as an
  255. // argument. This is a blocking function. Hook developers should
  256. // use 'go' keyword if they don't want to block Caddy.
  257. func EmitEvent(event EventName, info interface{}) {
  258. eventHooks.Range(func(k, v interface{}) bool {
  259. err := v.(EventHook)(event, info)
  260. if err != nil {
  261. log.Printf("error on '%s' hook: %v", k.(string), err)
  262. }
  263. return true
  264. })
  265. }
  266. // cloneEventHooks return a clone of the event hooks *sync.Map
  267. func cloneEventHooks() *sync.Map {
  268. c := &sync.Map{}
  269. eventHooks.Range(func(k, v interface{}) bool {
  270. c.Store(k, v)
  271. return true
  272. })
  273. return c
  274. }
  275. // purgeEventHooks purges all event hooks from the map
  276. func purgeEventHooks() {
  277. eventHooks.Range(func(k, _ interface{}) bool {
  278. eventHooks.Delete(k)
  279. return true
  280. })
  281. }
  282. // restoreEventHooks restores eventHooks with a provided *sync.Map
  283. func restoreEventHooks(m *sync.Map) {
  284. // Purge old event hooks
  285. purgeEventHooks()
  286. // Restore event hooks
  287. m.Range(func(k, v interface{}) bool {
  288. eventHooks.Store(k, v)
  289. return true
  290. })
  291. }
  292. // ParsingCallback is a function that is called after
  293. // a directive's setup functions have been executed
  294. // for all the server blocks.
  295. type ParsingCallback func(Context) error
  296. // RegisterParsingCallback registers callback to be called after
  297. // executing the directive afterDir for server type serverType.
  298. func RegisterParsingCallback(serverType, afterDir string, callback ParsingCallback) {
  299. if _, ok := parsingCallbacks[serverType]; !ok {
  300. parsingCallbacks[serverType] = make(map[string][]ParsingCallback)
  301. }
  302. parsingCallbacks[serverType][afterDir] = append(parsingCallbacks[serverType][afterDir], callback)
  303. }
  304. // SetupFunc is used to set up a plugin, or in other words,
  305. // execute a directive. It will be called once per key for
  306. // each server block it appears in.
  307. type SetupFunc func(c *Controller) error
  308. // DirectiveAction gets the action for directive dir of
  309. // server type serverType.
  310. func DirectiveAction(serverType, dir string) (SetupFunc, error) {
  311. if stypePlugins, ok := plugins[serverType]; ok {
  312. if plugin, ok := stypePlugins[dir]; ok {
  313. return plugin.Action, nil
  314. }
  315. }
  316. if genericPlugins, ok := plugins[""]; ok {
  317. if plugin, ok := genericPlugins[dir]; ok {
  318. return plugin.Action, nil
  319. }
  320. }
  321. return nil, fmt.Errorf("no action found for directive '%s' with server type '%s' (missing a plugin?)",
  322. dir, serverType)
  323. }
  324. // Loader is a type that can load a Caddyfile.
  325. // It is passed the name of the server type.
  326. // It returns an error only if something went
  327. // wrong, not simply if there is no Caddyfile
  328. // for this loader to load.
  329. //
  330. // A Loader should only load the Caddyfile if
  331. // a certain condition or requirement is met,
  332. // as returning a non-nil Input value along with
  333. // another Loader will result in an error.
  334. // In other words, loading the Caddyfile must
  335. // be deliberate & deterministic, not haphazard.
  336. //
  337. // The exception is the default Caddyfile loader,
  338. // which will be called only if no other Caddyfile
  339. // loaders return a non-nil Input. The default
  340. // loader may always return an Input value.
  341. type Loader interface {
  342. Load(serverType string) (Input, error)
  343. }
  344. // LoaderFunc is a convenience type similar to http.HandlerFunc
  345. // that allows you to use a plain function as a Load() method.
  346. type LoaderFunc func(serverType string) (Input, error)
  347. // Load loads a Caddyfile.
  348. func (lf LoaderFunc) Load(serverType string) (Input, error) {
  349. return lf(serverType)
  350. }
  351. // RegisterCaddyfileLoader registers loader named name.
  352. func RegisterCaddyfileLoader(name string, loader Loader) {
  353. caddyfileLoaders = append(caddyfileLoaders, caddyfileLoader{name: name, loader: loader})
  354. }
  355. // SetDefaultCaddyfileLoader registers loader by name
  356. // as the default Caddyfile loader if no others produce
  357. // a Caddyfile. If another Caddyfile loader has already
  358. // been set as the default, this replaces it.
  359. //
  360. // Do not call RegisterCaddyfileLoader on the same
  361. // loader; that would be redundant.
  362. func SetDefaultCaddyfileLoader(name string, loader Loader) {
  363. defaultCaddyfileLoader = caddyfileLoader{name: name, loader: loader}
  364. }
  365. // loadCaddyfileInput iterates the registered Caddyfile loaders
  366. // and, if needed, calls the default loader, to load a Caddyfile.
  367. // It is an error if any of the loaders return an error or if
  368. // more than one loader returns a Caddyfile.
  369. func loadCaddyfileInput(serverType string) (Input, error) {
  370. var loadedBy string
  371. var caddyfileToUse Input
  372. for _, l := range caddyfileLoaders {
  373. cdyfile, err := l.loader.Load(serverType)
  374. if err != nil {
  375. return nil, fmt.Errorf("loading Caddyfile via %s: %v", l.name, err)
  376. }
  377. if cdyfile != nil {
  378. if caddyfileToUse != nil {
  379. return nil, fmt.Errorf("Caddyfile loaded multiple times; first by %s, then by %s", loadedBy, l.name)
  380. }
  381. loaderUsed = l
  382. caddyfileToUse = cdyfile
  383. loadedBy = l.name
  384. }
  385. }
  386. if caddyfileToUse == nil && defaultCaddyfileLoader.loader != nil {
  387. cdyfile, err := defaultCaddyfileLoader.loader.Load(serverType)
  388. if err != nil {
  389. return nil, err
  390. }
  391. if cdyfile != nil {
  392. loaderUsed = defaultCaddyfileLoader
  393. caddyfileToUse = cdyfile
  394. }
  395. }
  396. return caddyfileToUse, nil
  397. }
  398. // OnProcessExit is a list of functions to run when the process
  399. // exits -- they are ONLY for cleanup and should not block,
  400. // return errors, or do anything fancy. They will be run with
  401. // every signal, even if "shutdown callbacks" are not executed.
  402. // This variable must only be modified in the main goroutine
  403. // from init() functions.
  404. var OnProcessExit []func()
  405. // caddyfileLoader pairs the name of a loader to the loader.
  406. type caddyfileLoader struct {
  407. name string
  408. loader Loader
  409. }
  410. var (
  411. defaultCaddyfileLoader caddyfileLoader // the default loader if all else fail
  412. loaderUsed caddyfileLoader // the loader that was used (relevant for reloads)
  413. )