Debian Codegraph @

context.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
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
15 package caddy
16
17 import (
18 "context"
19 "encoding/json"
20 "fmt"
21 "log"
22 "log/slog"
23 "reflect"
24 "sync"
25
26 "github.com/caddyserver/certmagic"
27 "github.com/prometheus/client_golang/prometheus"
28 "github.com/prometheus/client_golang/prometheus/collectors"
29 "go.uber.org/zap"
30 "go.uber.org/zap/exp/zapslog"
31 "go.uber.org/zap/zapcore"
32
33 "github.com/caddyserver/caddy/v2/internal/filesystems"
34 )
35
36 // Context is a type which defines the lifetime of modules that
37 // are loaded and provides access to the parent configuration
38 // that spawned the modules which are loaded. It should be used
39 // with care and wrapped with derivation functions from the
40 // standard context package only if you don't need the Caddy
41 // specific features. These contexts are canceled when the
42 // lifetime of the modules loaded from it is over.
43 //
44 // Use NewContext() to get a valid value (but most modules will
45 // not actually need to do this).
46 type Context struct {
47 context.Context
48
49 moduleInstances map[string][]Module
50 cfg *Config
51 ancestry []Module
52 cleanupFuncs []func() // invoked at every config unload
53 exitFuncs []func(context.Context) // invoked at config unload ONLY IF the process is exiting (EXPERIMENTAL)
54 metricsRegistry *prometheus.Registry
55 }
56
57 // NewContext provides a new context derived from the given
58 // context ctx. Normally, you will not need to call this
59 // function unless you are loading modules which have a
60 // different lifespan than the ones for the context the
61 // module was provisioned with. Be sure to call the cancel
62 // func when the context is to be cleaned up so that
63 // modules which are loaded will be properly unloaded.
64 // See standard library context package's documentation.
65 func NewContext(ctx Context) (Context, context.CancelFunc) {
66 newCtx, cancelCause := NewContextWithCause(ctx)
67 return newCtx, func() { cancelCause(nil) }
68 }
69
70 // NewContextWithCause is like NewContext but returns a context.CancelCauseFunc.
71 // EXPERIMENTAL: This API is subject to change.
72 func NewContextWithCause(ctx Context) (Context, context.CancelCauseFunc) {
73 newCtx := Context{moduleInstances: make(map[string][]Module), cfg: ctx.cfg, metricsRegistry: prometheus.NewPedanticRegistry()}
74 c, cancel := context.WithCancelCause(ctx.Context)
75 wrappedCancel := func(cause error) {
76 cancel(cause)
77
78 for _, f := range ctx.cleanupFuncs {
79 f()
80 }
81
82 for modName, modInstances := range newCtx.moduleInstances {
83 for _, inst := range modInstances {
84 if cu, ok := inst.(CleanerUpper); ok {
85 err := cu.Cleanup()
86 if err != nil {
87 log.Printf("[ERROR] %s (%p): cleanup: %v", modName, inst, err)
88 }
89 }
90 }
91 }
92 }
93 newCtx.Context = c
94 newCtx.initMetrics()
95 return newCtx, wrappedCancel
96 }
97
98 // OnCancel executes f when ctx is canceled.
99 func (ctx *Context) OnCancel(f func()) {
100 ctx.cleanupFuncs = append(ctx.cleanupFuncs, f)
101 }
102
103 // FileSystems returns a ref to the FilesystemMap.
104 // EXPERIMENTAL: This API is subject to change.
105 func (ctx *Context) FileSystems() FileSystems {
106 // if no config is loaded, we use a default filesystemmap, which includes the osfs
107 if ctx.cfg == nil {
108 return &filesystems.FileSystemMap{}
109 }
110 return ctx.cfg.fileSystems
111 }
112
113 // Returns the active metrics registry for the context
114 // EXPERIMENTAL: This API is subject to change.
115 func (ctx *Context) GetMetricsRegistry() *prometheus.Registry {
116 return ctx.metricsRegistry
117 }
118
119 func (ctx *Context) initMetrics() {
120 ctx.metricsRegistry.MustRegister(
121 collectors.NewBuildInfoCollector(),
122 collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
123 collectors.NewGoCollector(),
124 adminMetrics.requestCount,
125 adminMetrics.requestErrors,
126 globalMetrics.configSuccess,
127 globalMetrics.configSuccessTime,
128 )
129 }
130
131 // OnExit executes f when the process exits gracefully.
132 // The function is only executed if the process is gracefully
133 // shut down while this context is active.
134 //
135 // EXPERIMENTAL API: subject to change or removal.
136 func (ctx *Context) OnExit(f func(context.Context)) {
137 ctx.exitFuncs = append(ctx.exitFuncs, f)
138 }
139
140 // LoadModule loads the Caddy module(s) from the specified field of the parent struct
141 // pointer and returns the loaded module(s). The struct pointer and its field name as
142 // a string are necessary so that reflection can be used to read the struct tag on the
143 // field to get the module namespace and inline module name key (if specified).
144 //
145 // The field can be any one of the supported raw module types: json.RawMessage,
146 // []json.RawMessage, map[string]json.RawMessage, or []map[string]json.RawMessage.
147 // ModuleMap may be used in place of map[string]json.RawMessage. The return value's
148 // underlying type mirrors the input field's type:
149 //
150 // json.RawMessage => any
151 // []json.RawMessage => []any
152 // [][]json.RawMessage => [][]any
153 // map[string]json.RawMessage => map[string]any
154 // []map[string]json.RawMessage => []map[string]any
155 //
156 // The field must have a "caddy" struct tag in this format:
157 //
158 // caddy:"key1=val1 key2=val2"
159 //
160 // To load modules, a "namespace" key is required. For example, to load modules
161 // in the "http.handlers" namespace, you'd put: `namespace=http.handlers` in the
162 // Caddy struct tag.
163 //
164 // The module name must also be available. If the field type is a map or slice of maps,
165 // then key is assumed to be the module name if an "inline_key" is NOT specified in the
166 // caddy struct tag. In this case, the module name does NOT need to be specified in-line
167 // with the module itself.
168 //
169 // If not a map, or if inline_key is non-empty, then the module name must be embedded
170 // into the values, which must be objects; then there must be a key in those objects
171 // where its associated value is the module name. This is called the "inline key",
172 // meaning the key containing the module's name that is defined inline with the module
173 // itself. You must specify the inline key in a struct tag, along with the namespace:
174 //
175 // caddy:"namespace=http.handlers inline_key=handler"
176 //
177 // This will look for a key/value pair like `"handler": "..."` in the json.RawMessage
178 // in order to know the module name.
179 //
180 // To make use of the loaded module(s) (the return value), you will probably want
181 // to type-assert each 'any' value(s) to the types that are useful to you
182 // and store them on the same struct. Storing them on the same struct makes for
183 // easy garbage collection when your host module is no longer needed.
184 //
185 // Loaded modules have already been provisioned and validated. Upon returning
186 // successfully, this method clears the json.RawMessage(s) in the field since
187 // the raw JSON is no longer needed, and this allows the GC to free up memory.
188 func (ctx Context) LoadModule(structPointer any, fieldName string) (any, error) {
189 val := reflect.ValueOf(structPointer).Elem().FieldByName(fieldName)
190 typ := val.Type()
191
192 field, ok := reflect.TypeOf(structPointer).Elem().FieldByName(fieldName)
193 if !ok {
194 panic(fmt.Sprintf("field %s does not exist in %#v", fieldName, structPointer))
195 }
196
197 opts, err := ParseStructTag(field.Tag.Get("caddy"))
198 if err != nil {
199 panic(fmt.Sprintf("malformed tag on field %s: %v", fieldName, err))
200 }
201
202 moduleNamespace, ok := opts["namespace"]
203 if !ok {
204 panic(fmt.Sprintf("missing 'namespace' key in struct tag on field %s", fieldName))
205 }
206 inlineModuleKey := opts["inline_key"]
207
208 var result any
209
210 switch val.Kind() {
211 case reflect.Slice:
212 if isJSONRawMessage(typ) {
213 // val is `json.RawMessage` ([]uint8 under the hood)
214
215 if inlineModuleKey == "" {
216 panic("unable to determine module name without inline_key when type is not a ModuleMap")
217 }
218 val, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, val.Interface().(json.RawMessage))
219 if err != nil {
220 return nil, err
221 }
222 result = val
223 } else if isJSONRawMessage(typ.Elem()) {
224 // val is `[]json.RawMessage`
225
226 if inlineModuleKey == "" {
227 panic("unable to determine module name without inline_key because type is not a ModuleMap")
228 }
229 var all []any
230 for i := 0; i < val.Len(); i++ {
231 val, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, val.Index(i).Interface().(json.RawMessage))
232 if err != nil {
233 return nil, fmt.Errorf("position %d: %v", i, err)
234 }
235 all = append(all, val)
236 }
237 result = all
238 } else if typ.Elem().Kind() == reflect.Slice && isJSONRawMessage(typ.Elem().Elem()) {
239 // val is `[][]json.RawMessage`
240
241 if inlineModuleKey == "" {
242 panic("unable to determine module name without inline_key because type is not a ModuleMap")
243 }
244 var all [][]any
245 for i := 0; i < val.Len(); i++ {
246 innerVal := val.Index(i)
247 var allInner []any
248 for j := 0; j < innerVal.Len(); j++ {
249 innerInnerVal, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, innerVal.Index(j).Interface().(json.RawMessage))
250 if err != nil {
251 return nil, fmt.Errorf("position %d: %v", j, err)
252 }
253 allInner = append(allInner, innerInnerVal)
254 }
255 all = append(all, allInner)
256 }
257 result = all
258 } else if isModuleMapType(typ.Elem()) {
259 // val is `[]map[string]json.RawMessage`
260
261 var all []map[string]any
262 for i := 0; i < val.Len(); i++ {
263 thisSet, err := ctx.loadModulesFromSomeMap(moduleNamespace, inlineModuleKey, val.Index(i))
264 if err != nil {
265 return nil, err
266 }
267 all = append(all, thisSet)
268 }
269 result = all
270 }
271
272 case reflect.Map:
273 // val is a ModuleMap or some other kind of map
274 result, err = ctx.loadModulesFromSomeMap(moduleNamespace, inlineModuleKey, val)
275 if err != nil {
276 return nil, err
277 }
278
279 default:
280 return nil, fmt.Errorf("unrecognized type for module: %s", typ)
281 }
282
283 // we're done with the raw bytes; allow GC to deallocate
284 val.Set(reflect.Zero(typ))
285
286 return result, nil
287 }
288
289 // emitEvent is a small convenience method so the caddy core can emit events, if the event app is configured.
290 func (ctx Context) emitEvent(name string, data map[string]any) Event {
291 if ctx.cfg == nil || ctx.cfg.eventEmitter == nil {
292 return Event{}
293 }
294 return ctx.cfg.eventEmitter.Emit(ctx, name, data)
295 }
296
297 // loadModulesFromSomeMap loads modules from val, which must be a type of map[string]any.
298 // Depending on inlineModuleKey, it will be interpreted as either a ModuleMap (key is the module
299 // name) or as a regular map (key is not the module name, and module name is defined inline).
300 func (ctx Context) loadModulesFromSomeMap(namespace, inlineModuleKey string, val reflect.Value) (map[string]any, error) {
301 // if no inline_key is specified, then val must be a ModuleMap,
302 // where the key is the module name
303 if inlineModuleKey == "" {
304 if !isModuleMapType(val.Type()) {
305 panic(fmt.Sprintf("expected ModuleMap because inline_key is empty; but we do not recognize this type: %s", val.Type()))
306 }
307 return ctx.loadModuleMap(namespace, val)
308 }
309
310 // otherwise, val is a map with modules, but the module name is
311 // inline with each value (the key means something else)
312 return ctx.loadModulesFromRegularMap(namespace, inlineModuleKey, val)
313 }
314
315 // loadModulesFromRegularMap loads modules from val, where val is a map[string]json.RawMessage.
316 // Map keys are NOT interpreted as module names, so module names are still expected to appear
317 // inline with the objects.
318 func (ctx Context) loadModulesFromRegularMap(namespace, inlineModuleKey string, val reflect.Value) (map[string]any, error) {
319 mods := make(map[string]any)
320 iter := val.MapRange()
321 for iter.Next() {
322 k := iter.Key()
323 v := iter.Value()
324 mod, err := ctx.loadModuleInline(inlineModuleKey, namespace, v.Interface().(json.RawMessage))
325 if err != nil {
326 return nil, fmt.Errorf("key %s: %v", k, err)
327 }
328 mods[k.String()] = mod
329 }
330 return mods, nil
331 }
332
333 // loadModuleMap loads modules from a ModuleMap, i.e. map[string]any, where the key is the
334 // module name. With a module map, module names do not need to be defined inline with their values.
335 func (ctx Context) loadModuleMap(namespace string, val reflect.Value) (map[string]any, error) {
336 all := make(map[string]any)
337 iter := val.MapRange()
338 for iter.Next() {
339 k := iter.Key().Interface().(string)
340 v := iter.Value().Interface().(json.RawMessage)
341 moduleName := namespace + "." + k
342 if namespace == "" {
343 moduleName = k
344 }
345 val, err := ctx.LoadModuleByID(moduleName, v)
346 if err != nil {
347 return nil, fmt.Errorf("module name '%s': %v", k, err)
348 }
349 all[k] = val
350 }
351 return all, nil
352 }
353
354 // LoadModuleByID decodes rawMsg into a new instance of mod and
355 // returns the value. If mod.New is nil, an error is returned.
356 // If the module implements Validator or Provisioner interfaces,
357 // those methods are invoked to ensure the module is fully
358 // configured and valid before being used.
359 //
360 // This is a lower-level method and will usually not be called
361 // directly by most modules. However, this method is useful when
362 // dynamically loading/unloading modules in their own context,
363 // like from embedded scripts, etc.
364 func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (any, error) {
365 modulesMu.RLock()
366 modInfo, ok := modules[id]
367 modulesMu.RUnlock()
368 if !ok {
369 return nil, fmt.Errorf("unknown module: %s", id)
370 }
371
372 if modInfo.New == nil {
373 return nil, fmt.Errorf("module '%s' has no constructor", modInfo.ID)
374 }
375
376 val := modInfo.New()
377
378 // value must be a pointer for unmarshaling into concrete type, even if
379 // the module's concrete type is a slice or map; New() *should* return
380 // a pointer, otherwise unmarshaling errors or panics will occur
381 if rv := reflect.ValueOf(val); rv.Kind() != reflect.Pointer {
382 log.Printf("[WARNING] ModuleInfo.New() for module '%s' did not return a pointer,"+
383 " so we are using reflection to make a pointer instead; please fix this by"+
384 " using new(Type) or &Type notation in your module's New() function.", id)
385 val = reflect.New(rv.Type()).Elem().Addr().Interface().(Module)
386 }
387
388 // fill in its config only if there is a config to fill in
389 if len(rawMsg) > 0 {
390 err := StrictUnmarshalJSON(rawMsg, &val)
391 if err != nil {
392 return nil, fmt.Errorf("decoding module config: %s: %v", modInfo, err)
393 }
394 }
395
396 if val == nil {
397 // returned module values are almost always type-asserted
398 // before being used, so a nil value would panic; and there
399 // is no good reason to explicitly declare null modules in
400 // a config; it might be because the user is trying to achieve
401 // a result the developer isn't expecting, which is a smell
402 return nil, fmt.Errorf("module value cannot be null")
403 }
404
405 var err error
406
407 // if this is an app module, keep a reference to it,
408 // since submodules may need to reference it during
409 // provisioning (even though the parent app module
410 // may not be fully provisioned yet; this is the case
411 // with the tls app's automation policies, which may
412 // refer to the tls app to check if a global DNS
413 // module has been configured for DNS challenges)
414 if appModule, ok := val.(App); ok {
415 ctx.cfg.apps[id] = appModule
416 defer func() {
417 if err != nil {
418 ctx.cfg.failedApps[id] = err
419 }
420 }()
421 }
422
423 ctx.ancestry = append(ctx.ancestry, val)
424
425 if prov, ok := val.(Provisioner); ok {
426 err = prov.Provision(ctx)
427 if err != nil {
428 // incomplete provisioning could have left state
429 // dangling, so make sure it gets cleaned up
430 if cleanerUpper, ok := val.(CleanerUpper); ok {
431 err2 := cleanerUpper.Cleanup()
432 if err2 != nil {
433 err = fmt.Errorf("%v; additionally, cleanup: %v", err, err2)
434 }
435 }
436 return nil, fmt.Errorf("provision %s: %v", modInfo, err)
437 }
438 }
439
440 if validator, ok := val.(Validator); ok {
441 err = validator.Validate()
442 if err != nil {
443 // since the module was already provisioned, make sure we clean up
444 if cleanerUpper, ok := val.(CleanerUpper); ok {
445 err2 := cleanerUpper.Cleanup()
446 if err2 != nil {
447 err = fmt.Errorf("%v; additionally, cleanup: %v", err, err2)
448 }
449 }
450 return nil, fmt.Errorf("%s: invalid configuration: %v", modInfo, err)
451 }
452 }
453
454 ctx.moduleInstances[id] = append(ctx.moduleInstances[id], val)
455
456 // if the loaded module happens to be an app that can emit events, store it so the
457 // core can have access to emit events without an import cycle
458 if ee, ok := val.(eventEmitter); ok {
459 if _, ok := ee.(App); ok {
460 ctx.cfg.eventEmitter = ee
461 }
462 }
463
464 return val, nil
465 }
466
467 // loadModuleInline loads a module from a JSON raw message which decodes to
468 // a map[string]any, where one of the object keys is moduleNameKey
469 // and the corresponding value is the module name (as a string) which can
470 // be found in the given scope. In other words, the module name is declared
471 // in-line with the module itself.
472 //
473 // This allows modules to be decoded into their concrete types and used when
474 // their names cannot be the unique key in a map, such as when there are
475 // multiple instances in the map or it appears in an array (where there are
476 // no custom keys). In other words, the key containing the module name is
477 // treated special/separate from all the other keys in the object.
478 func (ctx Context) loadModuleInline(moduleNameKey, moduleScope string, raw json.RawMessage) (any, error) {
479 moduleName, raw, err := getModuleNameInline(moduleNameKey, raw)
480 if err != nil {
481 return nil, err
482 }
483
484 val, err := ctx.LoadModuleByID(moduleScope+"."+moduleName, raw)
485 if err != nil {
486 return nil, fmt.Errorf("loading module '%s': %v", moduleName, err)
487 }
488
489 return val, nil
490 }
491
492 // App returns the configured app named name. If that app has
493 // not yet been loaded and provisioned, it will be immediately
494 // loaded and provisioned. If no app with that name is
495 // configured, a new empty one will be instantiated instead.
496 // (The app module must still be registered.) This must not be
497 // called during the Provision/Validate phase to reference a
498 // module's own host app (since the parent app module is still
499 // in the process of being provisioned, it is not yet ready).
500 //
501 // We return any type instead of the App type because it is NOT
502 // intended for the caller of this method to be the one to start
503 // or stop App modules. The caller is expected to assert to the
504 // concrete type.
505 func (ctx Context) App(name string) (any, error) {
506 // if the app failed to load before, return the cached error
507 if err, ok := ctx.cfg.failedApps[name]; ok {
508 return nil, fmt.Errorf("loading %s app module: %v", name, err)
509 }
510 if app, ok := ctx.cfg.apps[name]; ok {
511 return app, nil
512 }
513 appRaw := ctx.cfg.AppsRaw[name]
514 modVal, err := ctx.LoadModuleByID(name, appRaw)
515 if err != nil {
516 return nil, fmt.Errorf("loading %s app module: %v", name, err)
517 }
518 if appRaw != nil {
519 ctx.cfg.AppsRaw[name] = nil // allow GC to deallocate
520 }
521 return modVal, nil
522 }
523
524 // AppIfConfigured is like App, but it returns an error if the
525 // app has not been configured. This is useful when the app is
526 // required and its absence is a configuration error; or when
527 // the app is optional and you don't want to instantiate a
528 // new one that hasn't been explicitly configured. If the app
529 // is not in the configuration, the error wraps ErrNotConfigured.
530 func (ctx Context) AppIfConfigured(name string) (any, error) {
531 if ctx.cfg == nil {
532 return nil, fmt.Errorf("app module %s: %w", name, ErrNotConfigured)
533 }
534 // if the app failed to load before, return the cached error
535 if err, ok := ctx.cfg.failedApps[name]; ok {
536 return nil, fmt.Errorf("loading %s app module: %v", name, err)
537 }
538 if app, ok := ctx.cfg.apps[name]; ok {
539 return app, nil
540 }
541 appRaw := ctx.cfg.AppsRaw[name]
542 if appRaw == nil {
543 return nil, fmt.Errorf("app module %s: %w", name, ErrNotConfigured)
544 }
545 return ctx.App(name)
546 }
547
548 // ErrNotConfigured indicates a module is not configured.
549 var ErrNotConfigured = fmt.Errorf("module not configured")
550
551 // Storage returns the configured Caddy storage implementation.
552 func (ctx Context) Storage() certmagic.Storage {
553 return ctx.cfg.storage
554 }
555
556 // Logger returns a logger that is intended for use by the most
557 // recent module associated with the context. Callers should not
558 // pass in any arguments unless they want to associate with a
559 // different module; it panics if more than 1 value is passed in.
560 //
561 // Originally, this method's signature was `Logger(mod Module)`,
562 // requiring that an instance of a Caddy module be passed in.
563 // However, that is no longer necessary, as the closest module
564 // most recently associated with the context will be automatically
565 // assumed. To prevent a sudden breaking change, this method's
566 // signature has been changed to be variadic, but we may remove
567 // the parameter altogether in the future. Callers should not
568 // pass in any argument. If there is valid need to specify a
569 // different module, please open an issue to discuss.
570 //
571 // PARTIALLY DEPRECATED: The Logger(module) form is deprecated and
572 // may be removed in the future. Do not pass in any arguments.
573 func (ctx Context) Logger(module ...Module) *zap.Logger {
574 if len(module) > 1 {
575 panic("more than 1 module passed in")
576 }
577 if ctx.cfg == nil {
578 // often the case in tests; just use a dev logger
579 l, err := zap.NewDevelopment()
580 if err != nil {
581 panic("config missing, unable to create dev logger: " + err.Error())
582 }
583 return l
584 }
585 mod := ctx.Module()
586 if len(module) > 0 {
587 mod = module[0]
588 }
589 if mod == nil {
590 return Log()
591 }
592 return ctx.cfg.Logging.Logger(mod)
593 }
594
595 type slogHandlerFactory func(handler slog.Handler, core zapcore.Core, moduleID string) slog.Handler
596
597 var (
598 slogHandlerFactories []slogHandlerFactory
599 slogHandlerFactoriesMu sync.RWMutex
600 )
601
602 // RegisterSlogHandlerFactory allows modules to register custom log/slog.Handler,
603 // for instance, to add contextual data to the logs.
604 func RegisterSlogHandlerFactory(factory slogHandlerFactory) {
605 slogHandlerFactoriesMu.Lock()
606 slogHandlerFactories = append(slogHandlerFactories, factory)
607 slogHandlerFactoriesMu.Unlock()
608 }
609
610 // Slogger returns a slog logger that is intended for use by
611 // the most recent module associated with the context.
612 func (ctx Context) Slogger() *slog.Logger {
613 var (
614 handler slog.Handler
615 core zapcore.Core
616 moduleID string
617 )
618
619 // the default enables traces at ERROR level, this disables
620 // them by setting it to a level higher than any other level
621 tracesOpt := zapslog.AddStacktraceAt(slog.Level(127))
622
623 if ctx.cfg == nil {
624 // often the case in tests; just use a dev logger
625 l, err := zap.NewDevelopment()
626 if err != nil {
627 panic("config missing, unable to create dev logger: " + err.Error())
628 }
629
630 core = l.Core()
631 handler = zapslog.NewHandler(core, tracesOpt)
632 } else {
633 mod := ctx.Module()
634 if mod == nil {
635 core = Log().Core()
636 handler = zapslog.NewHandler(core, tracesOpt)
637 } else {
638 moduleID = string(mod.CaddyModule().ID)
639 core = ctx.cfg.Logging.Logger(mod).Core()
640 handler = zapslog.NewHandler(core, zapslog.WithName(moduleID), tracesOpt)
641 }
642 }
643
644 slogHandlerFactoriesMu.RLock()
645 for _, f := range slogHandlerFactories {
646 handler = f(handler, core, moduleID)
647 }
648 slogHandlerFactoriesMu.RUnlock()
649
650 return slog.New(handler)
651 }
652
653 // Modules returns the lineage of modules that this context provisioned,
654 // with the most recent/current module being last in the list.
655 func (ctx Context) Modules() []Module {
656 mods := make([]Module, len(ctx.ancestry))
657 copy(mods, ctx.ancestry)
658 return mods
659 }
660
661 // Module returns the current module, or the most recent one
662 // provisioned by the context.
663 func (ctx Context) Module() Module {
664 if len(ctx.ancestry) == 0 {
665 return nil
666 }
667 return ctx.ancestry[len(ctx.ancestry)-1]
668 }
669
670 // WithValue returns a new context with the given key-value pair.
671 func (ctx *Context) WithValue(key, value any) Context {
672 return Context{
673 Context: context.WithValue(ctx.Context, key, value),
674 moduleInstances: ctx.moduleInstances,
675 cfg: ctx.cfg,
676 ancestry: ctx.ancestry,
677 cleanupFuncs: ctx.cleanupFuncs,
678 exitFuncs: ctx.exitFuncs,
679 }
680 }
681
682 // eventEmitter is a small interface that inverts dependencies for
683 // the caddyevents package, so the core can emit events without an
684 // import cycle (i.e. the caddy package doesn't have to import
685 // the caddyevents package, which imports the caddy package).
686 type eventEmitter interface {
687 Emit(ctx Context, eventName string, data map[string]any) Event
688 }