restart.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "time"
  17. "github.com/docker/cli/cli/command"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose/v2/pkg/api"
  20. )
  21. type restartOptions struct {
  22. *ProjectOptions
  23. timeChanged bool
  24. timeout int
  25. noDeps bool
  26. }
  27. func restartCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  28. opts := restartOptions{
  29. ProjectOptions: p,
  30. }
  31. restartCmd := &cobra.Command{
  32. Use: "restart [OPTIONS] [SERVICE...]",
  33. Short: "Restart service containers",
  34. PreRun: func(cmd *cobra.Command, args []string) {
  35. opts.timeChanged = cmd.Flags().Changed("timeout")
  36. },
  37. RunE: Adapt(func(ctx context.Context, args []string) error {
  38. return runRestart(ctx, dockerCli, backend, opts, args)
  39. }),
  40. ValidArgsFunction: completeServiceNames(dockerCli, p),
  41. }
  42. flags := restartCmd.Flags()
  43. flags.IntVarP(&opts.timeout, "timeout", "t", 0, "Specify a shutdown timeout in seconds")
  44. flags.BoolVar(&opts.noDeps, "no-deps", false, "Don't restart dependent services")
  45. return restartCmd
  46. }
  47. func runRestart(ctx context.Context, dockerCli command.Cli, backend api.Service, opts restartOptions, services []string) error {
  48. project, name, err := opts.projectOrName(ctx, dockerCli)
  49. if err != nil {
  50. return err
  51. }
  52. if project != nil && len(services) > 0 {
  53. project, err = project.WithServicesEnabled(services...)
  54. if err != nil {
  55. return err
  56. }
  57. }
  58. var timeout *time.Duration
  59. if opts.timeChanged {
  60. timeoutValue := time.Duration(opts.timeout) * time.Second
  61. timeout = &timeoutValue
  62. }
  63. return backend.Restart(ctx, name, api.RestartOptions{
  64. Timeout: timeout,
  65. Services: services,
  66. Project: project,
  67. NoDeps: opts.noDeps,
  68. })
  69. }