github.com/containerd/nerdctl@v1.7.7/pkg/composer/restart.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package composer 18 19 import ( 20 "context" 21 "fmt" 22 "sync" 23 24 "github.com/compose-spec/compose-go/types" 25 "github.com/containerd/containerd" 26 "github.com/containerd/log" 27 "github.com/containerd/nerdctl/pkg/labels" 28 ) 29 30 // RestartOptions stores all option input from `nerdctl compose restart` 31 type RestartOptions struct { 32 Timeout *uint 33 } 34 35 // Restart restarts running/stopped containers in `services`. It calls 36 // `nerdctl restart CONTAINER_ID` to do the actual job. 37 func (c *Composer) Restart(ctx context.Context, opt RestartOptions, services []string) error { 38 // in dependency order 39 return c.project.WithServices(services, func(svc types.ServiceConfig) error { 40 containers, err := c.Containers(ctx, svc.Name) 41 if err != nil { 42 return err 43 } 44 45 return c.restartContainers(ctx, containers, opt) 46 }) 47 } 48 49 func (c *Composer) restartContainers(ctx context.Context, containers []containerd.Container, opt RestartOptions) error { 50 var timeoutArg string 51 if opt.Timeout != nil { 52 // `nerdctl restart` uses `--time` instead of `--timeout` 53 timeoutArg = fmt.Sprintf("--time=%d", *opt.Timeout) 54 } 55 56 var rsWG sync.WaitGroup 57 for _, container := range containers { 58 container := container 59 rsWG.Add(1) 60 go func() { 61 defer rsWG.Done() 62 info, _ := container.Info(ctx, containerd.WithoutRefreshedMetadata) 63 log.G(ctx).Infof("Restarting container %s", info.Labels[labels.Name]) 64 args := []string{"restart"} 65 if opt.Timeout != nil { 66 args = append(args, timeoutArg) 67 } 68 args = append(args, container.ID()) 69 if err := c.runNerdctlCmd(ctx, args...); err != nil { 70 log.G(ctx).Warn(err) 71 } 72 }() 73 } 74 rsWG.Wait() 75 76 return nil 77 }