Debian Codegraph @

cmd/commands.go

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
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 caddycmd
16
17 import (
18 "flag"
19 "fmt"
20 "os"
21 "regexp"
22 "strings"
23 "sync"
•24 "time"
25
26 "github.com/spf13/cobra"
27 "github.com/spf13/cobra/doc"
28
29 "github.com/caddyserver/caddy/v2"
30 )
31
•32 // CustomDate will be used by the cobra manpage generator to generate a
33 // reproducible timestamp. If the "Date" header passed to cobra is empty, it
34 // will derive the time at build time, which is not reproducible.
35 // can be passed to during `go build` with `-ldflags`:
36 //
37 // -ldflags '-X github.com/caddyserver/caddy/v2/cmd.CustomDate=DD.MM.YYYY'
38 var CustomDate string
39
40 // Command represents a subcommand. Name, Func,
41 // and Short are required.
42 type Command struct {
43 // The name of the subcommand. Must conform to the
44 // format described by the RegisterCommand() godoc.
45 // Required.
46 Name string
47
48 // Usage is a brief message describing the syntax of
49 // the subcommand's flags and args. Use [] to indicate
50 // optional parameters and <> to enclose literal values
51 // intended to be replaced by the user. Do not prefix
52 // the string with "caddy" or the name of the command
53 // since these will be prepended for you; only include
54 // the actual parameters for this command.
55 Usage string
56
57 // Short is a one-line message explaining what the
58 // command does. Should not end with punctuation.
59 // Required.
60 Short string
61
62 // Long is the full help text shown to the user.
63 // Will be trimmed of whitespace on both ends before
64 // being printed.
65 Long string
66
67 // Flags is the flagset for command.
68 // This is ignored if CobraFunc is set.
69 Flags *flag.FlagSet
70
71 // Func is a function that executes a subcommand using
72 // the parsed flags. It returns an exit code and any
73 // associated error.
74 // Required if CobraFunc is not set.
75 Func CommandFunc
76
77 // CobraFunc allows further configuration of the command
78 // via cobra's APIs. If this is set, then Func and Flags
79 // are ignored, with the assumption that they are set in
80 // this function. A caddycmd.WrapCommandFuncForCobra helper
81 // exists to simplify porting CommandFunc to Cobra's RunE.
82 CobraFunc func(*cobra.Command)
83 }
84
85 // CommandFunc is a command's function. It runs the
86 // command and returns the proper exit code along with
87 // any error that occurred.
88 type CommandFunc func(Flags) (int, error)
89
90 // Commands returns a list of commands initialised by
91 // RegisterCommand
92 func Commands() map[string]Command {
93 commandsMu.RLock()
94 defer commandsMu.RUnlock()
95
96 return commands
97 }
98
99 var (
100 commandsMu sync.RWMutex
101 commands = make(map[string]Command)
102 )
103
104 func init() {
105 RegisterCommand(Command{
106 Name: "start",
107 Usage: "[--config <path> [--adapter <name>]] [--envfile <path>] [--watch] [--pidfile <file>]",
108 Short: "Starts the Caddy process in the background and then returns",
109 Long: `
110 Starts the Caddy process, optionally bootstrapped with an initial config file.
111 This command unblocks after the server starts running or fails to run.
112
113 If --envfile is specified, an environment file with environment variables
114 in the KEY=VALUE format will be loaded into the Caddy process.
115
116 On Windows, the spawned child process will remain attached to the terminal, so
117 closing the window will forcefully stop Caddy; to avoid forgetting this, try
118 using 'caddy run' instead to keep it in the foreground.
119 `,
120 CobraFunc: func(cmd *cobra.Command) {
121 cmd.Flags().StringP("config", "c", "", "Configuration file")
122 cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply")
123 cmd.Flags().StringSliceP("envfile", "", []string{}, "Environment file(s) to load")
124 cmd.Flags().BoolP("watch", "w", false, "Reload changed config file automatically")
125 cmd.Flags().StringP("pidfile", "", "", "Path of file to which to write process ID")
126 cmd.RunE = WrapCommandFuncForCobra(cmdStart)
127 },
128 })
129
130 RegisterCommand(Command{
131 Name: "run",
132 Usage: "[--config <path> [--adapter <name>]] [--envfile <path>] [--environ] [--resume] [--watch] [--pidfile <file>]",
133 Short: `Starts the Caddy process and blocks indefinitely`,
134 Long: `
135 Starts the Caddy process, optionally bootstrapped with an initial config file,
136 and blocks indefinitely until the server is stopped; i.e. runs Caddy in
137 "daemon" mode (foreground).
138
139 If a config file is specified, it will be applied immediately after the process
140 is running. If the config file is not in Caddy's native JSON format, you can
141 specify an adapter with --adapter to adapt the given config file to
142 Caddy's native format. The config adapter must be a registered module. Any
143 warnings will be printed to the log, but beware that any adaptation without
144 errors will immediately be used. If you want to review the results of the
145 adaptation first, use the 'adapt' subcommand.
146
147 As a special case, if the current working directory has a file called
148 "Caddyfile" and the caddyfile config adapter is plugged in (default), then
149 that file will be loaded and used to configure Caddy, even without any command
150 line flags.
151
152 If --envfile is specified, an environment file with environment variables
153 in the KEY=VALUE format will be loaded into the Caddy process.
154
155 If --environ is specified, the environment as seen by the Caddy process will
156 be printed before starting. This is the same as the environ command but does
157 not quit after printing, and can be useful for troubleshooting.
158
159 The --resume flag will override the --config flag if there is a config auto-
160 save file. It is not an error if --resume is used and no autosave file exists.
161
162 If --watch is specified, the config file will be loaded automatically after
163 changes. ⚠️ This can make unintentional config changes easier; only use this
164 option in a local development environment.
165 `,
166 CobraFunc: func(cmd *cobra.Command) {
167 cmd.Flags().StringP("config", "c", "", "Configuration file")
168 cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply")
169 cmd.Flags().StringSliceP("envfile", "", []string{}, "Environment file(s) to load")
170 cmd.Flags().BoolP("environ", "e", false, "Print environment")
171 cmd.Flags().BoolP("resume", "r", false, "Use saved config, if any (and prefer over --config file)")
172 cmd.Flags().BoolP("watch", "w", false, "Watch config file for changes and reload it automatically")
173 cmd.Flags().StringP("pidfile", "", "", "Path of file to which to write process ID")
174 cmd.Flags().StringP("pingback", "", "", "Echo confirmation bytes to this address on success")
175 cmd.RunE = WrapCommandFuncForCobra(cmdRun)
176 },
177 })
178
179 RegisterCommand(Command{
180 Name: "stop",
181 Usage: "[--config <path> [--adapter <name>]] [--address <interface>]",
182 Short: "Gracefully stops a started Caddy process",
183 Long: `
184 Stops the background Caddy process as gracefully as possible.
185
186 It requires that the admin API is enabled and accessible, since it will
187 use the API's /stop endpoint. The address of this request can be customized
188 using the --address flag, or from the given --config, if not the default.
189 `,
190 CobraFunc: func(cmd *cobra.Command) {
191 cmd.Flags().StringP("config", "c", "", "Configuration file to use to parse the admin address, if --address is not used")
192 cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply (when --config is used)")
193 cmd.Flags().StringP("address", "", "", "The address to use to reach the admin API endpoint, if not the default")
194 cmd.RunE = WrapCommandFuncForCobra(cmdStop)
195 },
196 })
197
198 RegisterCommand(Command{
199 Name: "reload",
200 Usage: "--config <path> [--adapter <name>] [--address <interface>]",
201 Short: "Changes the config of the running Caddy instance",
202 Long: `
203 Gives the running Caddy instance a new configuration. This has the same effect
204 as POSTing a document to the /load API endpoint, but is convenient for simple
205 workflows revolving around config files.
206
207 Since the admin endpoint is configurable, the endpoint configuration is loaded
208 from the --address flag if specified; otherwise it is loaded from the given
209 config file; otherwise the default is assumed.
210 `,
211 CobraFunc: func(cmd *cobra.Command) {
212 cmd.Flags().StringP("config", "c", "", "Configuration file (required)")
213 cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply")
214 cmd.Flags().StringP("address", "", "", "Address of the administration listener, if different from config")
215 cmd.Flags().BoolP("force", "f", false, "Force config reload, even if it is the same")
216 cmd.RunE = WrapCommandFuncForCobra(cmdReload)
217 },
218 })
219
220 RegisterCommand(Command{
221 Name: "version",
222 Short: "Prints the version",
223 Long: `
224 Prints the version of this Caddy binary.
225
226 Version information must be embedded into the binary at compile-time in
227 order for Caddy to display anything useful with this command. If Caddy
228 is built from within a version control repository, the Go command will
229 embed the revision hash if available. However, if Caddy is built in the
230 way specified by our online documentation (or by using xcaddy), more
231 detailed version information is printed as given by Go modules.
232
233 For more details about the full version string, see the Go module
234 documentation: https://go.dev/doc/modules/version-numbers
235 `,
236 Func: cmdVersion,
237 })
238
239 RegisterCommand(Command{
240 Name: "list-modules",
241 Usage: "[--packages] [--versions] [--skip-standard] [--json]",
242 Short: "Lists the installed Caddy modules",
243 CobraFunc: func(cmd *cobra.Command) {
244 cmd.Flags().BoolP("packages", "", false, "Print package paths")
245 cmd.Flags().BoolP("versions", "", false, "Print version information")
246 cmd.Flags().BoolP("skip-standard", "s", false, "Skip printing standard modules")
247 cmd.Flags().BoolP("json", "", false, "Print modules in JSON format")
248 cmd.RunE = WrapCommandFuncForCobra(cmdListModules)
249 },
250 })
251
252 RegisterCommand(Command{
253 Name: "build-info",
254 Short: "Prints information about this build",
255 Func: cmdBuildInfo,
256 })
257
258 RegisterCommand(Command{
259 Name: "environ",
260 Usage: "[--envfile <path>]",
261 Short: "Prints the environment",
262 Long: `
263 Prints the environment as seen by this Caddy process.
264
265 The environment includes variables set in the system. If your Caddy
266 configuration uses environment variables (e.g. "{env.VARIABLE}") then
267 this command can be useful for verifying that the variables will have
268 the values you expect in your config.
269
270 If --envfile is specified, an environment file with environment variables
271 in the KEY=VALUE format will be loaded into the Caddy process.
272
273 Note that environments may be different depending on how you run Caddy.
274 Environments for Caddy instances started by service managers such as
275 systemd are often different than the environment inherited from your
276 shell or terminal.
277
278 You can also print the environment the same time you use "caddy run"
279 by adding the "--environ" flag.
280
281 Environments may contain sensitive data.
282 `,
283 CobraFunc: func(cmd *cobra.Command) {
284 cmd.Flags().StringSliceP("envfile", "", []string{}, "Environment file(s) to load")
285 cmd.RunE = WrapCommandFuncForCobra(cmdEnviron)
286 },
287 })
288
289 RegisterCommand(Command{
290 Name: "adapt",
291 Usage: "--config <path> [--adapter <name>] [--pretty] [--validate] [--envfile <path>]",
292 Short: "Adapts a configuration to Caddy's native JSON",
293 Long: `
294 Adapts a configuration to Caddy's native JSON format and writes the
295 output to stdout, along with any warnings to stderr.
296
297 If --pretty is specified, the output will be formatted with indentation
298 for human readability.
299
300 If --validate is used, the adapted config will be checked for validity.
301 If the config is invalid, an error will be printed to stderr and a non-
302 zero exit status will be returned.
303
304 If --envfile is specified, an environment file with environment variables
305 in the KEY=VALUE format will be loaded into the Caddy process.
306
307 If you wish to use stdin instead of a regular file, use - as the path.
308 `,
309 CobraFunc: func(cmd *cobra.Command) {
310 cmd.Flags().StringP("config", "c", "", "Configuration file to adapt (required)")
311 cmd.Flags().StringP("adapter", "a", "caddyfile", "Name of config adapter")
312 cmd.Flags().BoolP("pretty", "p", false, "Format the output for human readability")
313 cmd.Flags().BoolP("validate", "", false, "Validate the output")
314 cmd.Flags().StringSliceP("envfile", "", []string{}, "Environment file(s) to load")
315 cmd.RunE = WrapCommandFuncForCobra(cmdAdaptConfig)
316 },
317 })
318
319 RegisterCommand(Command{
320 Name: "validate",
321 Usage: "--config <path> [--adapter <name>] [--envfile <path>]",
322 Short: "Tests whether a configuration file is valid",
323 Long: `
324 Loads and provisions the provided config, but does not start running it.
325 This reveals any errors with the configuration through the loading and
326 provisioning stages.
327
328 If --envfile is specified, an environment file with environment variables
329 in the KEY=VALUE format will be loaded into the Caddy process.
330 `,
331 CobraFunc: func(cmd *cobra.Command) {
332 cmd.Flags().StringP("config", "c", "", "Input configuration file")
333 cmd.Flags().StringP("adapter", "a", "", "Name of config adapter")
334 cmd.Flags().StringSliceP("envfile", "", []string{}, "Environment file(s) to load")
335 cmd.RunE = WrapCommandFuncForCobra(cmdValidateConfig)
336 },
337 })
338
339 RegisterCommand(Command{
340 Name: "storage",
341 Short: "Commands for working with Caddy's storage (EXPERIMENTAL)",
342 Long: `
343 Allows exporting and importing Caddy's storage contents. The two commands can be
344 combined in a pipeline to transfer directly from one storage to another:
345
346 $ caddy storage export --config Caddyfile.old --output - |
347 > caddy storage import --config Caddyfile.new --input -
348
349 The - argument refers to stdout and stdin, respectively.
350
351 NOTE: When importing to or exporting from file_system storage (the default), the command
352 should be run as the user that owns the associated root path.
353
354 EXPERIMENTAL: May be changed or removed.
355 `,
356 CobraFunc: func(cmd *cobra.Command) {
357 exportCmd := &cobra.Command{
358 Use: "export --config <path> --output <path>",
359 Short: "Exports storage assets as a tarball",
360 Long: `
361 The contents of the configured storage module (TLS certificates, etc)
362 are exported via a tarball.
363
364 --output is required, - can be given for stdout.
365 `,
366 RunE: WrapCommandFuncForCobra(cmdExportStorage),
367 }
368 exportCmd.Flags().StringP("config", "c", "", "Input configuration file (required)")
369 exportCmd.Flags().StringP("output", "o", "", "Output path")
370 cmd.AddCommand(exportCmd)
371
372 importCmd := &cobra.Command{
373 Use: "import --config <path> --input <path>",
374 Short: "Imports storage assets from a tarball.",
375 Long: `
376 Imports storage assets to the configured storage module. The import file must be
377 a tar archive.
378
379 --input is required, - can be given for stdin.
380 `,
381 RunE: WrapCommandFuncForCobra(cmdImportStorage),
382 }
383 importCmd.Flags().StringP("config", "c", "", "Configuration file to load (required)")
384 importCmd.Flags().StringP("input", "i", "", "Tar of assets to load (required)")
385 cmd.AddCommand(importCmd)
386 },
387 })
388
389 RegisterCommand(Command{
390 Name: "fmt",
391 Usage: "[--overwrite] [--diff] [<path>]",
392 Short: "Formats a Caddyfile",
393 Long: `
394 Formats the Caddyfile by adding proper indentation and spaces to improve
395 human readability. It prints the result to stdout.
396
397 If --overwrite is specified, the output will be written to the config file
398 directly instead of printing it.
399
400 If --diff is specified, the output will be compared against the input, and
401 lines will be prefixed with '-' and '+' where they differ. Note that
402 unchanged lines are prefixed with two spaces for alignment, and that this
403 is not a valid patch format.
404
405 If you wish to use stdin instead of a regular file, use - as the path.
406 When reading from stdin, the --overwrite flag has no effect: the result
407 is always printed to stdout.
408 `,
409 CobraFunc: func(cmd *cobra.Command) {
410 cmd.Flags().StringP("config", "c", "", "Configuration file")
411 cmd.Flags().BoolP("overwrite", "w", false, "Overwrite the input file with the results")
412 cmd.Flags().BoolP("diff", "d", false, "Print the differences between the input file and the formatted output")
413 cmd.RunE = WrapCommandFuncForCobra(cmdFmt)
414 },
415 })
416
417 defaultFactory.Use(func(rootCmd *cobra.Command) {
418 manpageCommand := Command{
419 Name: "manpage",
420 Usage: "--directory <path>",
421 Short: "Generates the manual pages for Caddy commands",
422 Long: `
423 Generates the manual pages for Caddy commands into the designated directory
424 tagged into section 8 (System Administration).
425
426 The manual page files are generated into the directory specified by the
427 argument of --directory. If the directory does not exist, it will be created.
428 `,
429 CobraFunc: func(cmd *cobra.Command) {
430 cmd.Flags().StringP("directory", "o", "", "The output directory where the manpages are generated")
431 cmd.RunE = WrapCommandFuncForCobra(func(fl Flags) (int, error) {
432 dir := strings.TrimSpace(fl.String("directory"))
433 if dir == "" {
434 return caddy.ExitCodeFailedQuit, fmt.Errorf("designated output directory and specified section are required")
435 }
436 if err := os.MkdirAll(dir, 0o755); err != nil {
437 return caddy.ExitCodeFailedQuit, err
438 }
•439 if CustomDate != "" {
440 date, _ := time.Parse(time.RFC3339, CustomDate)
441 if err := doc.GenManTree(rootCmd, &doc.GenManHeader{
442 Title: "Caddy",
443 Section: "8", // https://en.wikipedia.org/wiki/Man_page#Manual_sections
444 Date: &date,
445 }, dir); err != nil {
446 return caddy.ExitCodeFailedQuit, err
447 }
448 } else if err := doc.GenManTree(rootCmd, &doc.GenManHeader{
449 Title: "Caddy",
450 Section: "8", // https://en.wikipedia.org/wiki/Man_page#Manual_sections
451 }, dir); err != nil {
452 return caddy.ExitCodeFailedQuit, err
453 }
454 return caddy.ExitCodeSuccess, nil
455 })
456 },
457 }
458
459 // source: https://github.com/spf13/cobra/blob/6dec1ae26659a130bdb4c985768d1853b0e1bc06/site/content/completions/_index.md
460 completionCommand := Command{
461 Name: "completion",
462 Usage: "[bash|zsh|fish|powershell]",
463 Short: "Generate completion script",
464 Long: fmt.Sprintf(`To load completions:
465
466 Bash:
467
468 $ source <(%[1]s completion bash)
469
470 # To load completions for each session, execute once:
471 # Linux:
472 $ %[1]s completion bash > /etc/bash_completion.d/%[1]s
473 # macOS:
474 $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
475
476 Zsh:
477
478 # If shell completion is not already enabled in your environment,
479 # you will need to enable it. You can execute the following once:
480
481 $ echo "autoload -U compinit; compinit" >> ~/.zshrc
482
483 # To load completions for each session, execute once:
484 $ %[1]s completion zsh > "${fpath[1]}/_%[1]s"
485
486 # You will need to start a new shell for this setup to take effect.
487
488 fish:
489
490 $ %[1]s completion fish | source
491
492 # To load completions for each session, execute once:
493 $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
494
495 PowerShell:
496
497 PS> %[1]s completion powershell | Out-String | Invoke-Expression
498
499 # To load completions for every new session, run:
500 PS> %[1]s completion powershell > %[1]s.ps1
501 # and source this file from your PowerShell profile.
502 `, rootCmd.Root().Name()),
503 CobraFunc: func(cmd *cobra.Command) {
504 cmd.DisableFlagsInUseLine = true
505 cmd.ValidArgs = []string{"bash", "zsh", "fish", "powershell"}
506 cmd.Args = cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs)
507 cmd.RunE = func(cmd *cobra.Command, args []string) error {
508 switch args[0] {
509 case "bash":
510 return cmd.Root().GenBashCompletion(os.Stdout)
511 case "zsh":
512 return cmd.Root().GenZshCompletion(os.Stdout)
513 case "fish":
514 return cmd.Root().GenFishCompletion(os.Stdout, true)
515 case "powershell":
516 return cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
517 default:
518 return fmt.Errorf("unrecognized shell: %s", args[0])
519 }
520 }
521 },
522 }
523
524 rootCmd.AddCommand(caddyCmdToCobra(manpageCommand))
525 rootCmd.AddCommand(caddyCmdToCobra(completionCommand))
526
527 // add manpage and completion commands to the map of
528 // available commands, because they're not registered
529 // through RegisterCommand.
530 commandsMu.Lock()
531 commands[manpageCommand.Name] = manpageCommand
532 commands[completionCommand.Name] = completionCommand
533 commandsMu.Unlock()
534 })
535 }
536
537 // RegisterCommand registers the command cmd.
538 // cmd.Name must be unique and conform to the
539 // following format:
540 //
541 // - lowercase
542 // - ASCII lowercase letters, digits and hyphens only
543 // - cannot start or end with a hyphen
544 // - hyphen cannot be adjacent to another hyphen
545 //
546 // This function panics if the name is already registered,
547 // if the name does not meet the described format, or if
548 // any of the fields are missing from cmd.
549 //
550 // This function should be used in init().
551 func RegisterCommand(cmd Command) {
552 commandsMu.Lock()
553 defer commandsMu.Unlock()
554
555 if cmd.Name == "" {
556 panic("command name is required")
557 }
558 if cmd.Func == nil && cmd.CobraFunc == nil {
559 panic("command function missing")
560 }
561 if cmd.Short == "" {
562 panic("command short string is required")
563 }
564 if _, exists := commands[cmd.Name]; exists {
565 panic("command already registered: " + cmd.Name)
566 }
567 if !commandNameRegex.MatchString(cmd.Name) {
568 panic("invalid command name")
569 }
570 defaultFactory.Use(func(rootCmd *cobra.Command) {
571 rootCmd.AddCommand(caddyCmdToCobra(cmd))
572 })
573 commands[cmd.Name] = cmd
574 }
575
576 var commandNameRegex = regexp.MustCompile(`^[a-z0-9]$|^([a-z0-9]+-?[a-z0-9]*)+[a-z0-9]$`)