Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ It does not necessarily mean that the corresponding features are missing in cont
- [:whale: nerdctl port](#whale-nerdctl-port)
- [:whale: nerdctl rm](#whale-nerdctl-rm)
- [:whale: nerdctl stop](#whale-nerdctl-stop)
- [:whale: nerdctl start](#whale-nerdctl-start)
- [:whale: nerdctl kill](#whale-nerdctl-kill)
- [:whale: nerdctl pause](#whale-nerdctl-pause)
- [:whale: nerdctl unpause](#whale-nerdctl-unpause)
Expand Down Expand Up @@ -306,6 +307,9 @@ Flags:
### :whale: nerdctl stop
Stop one or more running containers.

### :whale: nerdctl start
Start one or more running containers.

### :whale: nerdctl kill
Kill one or more running containers.

Expand Down Expand Up @@ -468,7 +472,6 @@ Container management:
- `docker cp`
- `docker diff`
- `docker rename`
- `docker start`
- `docker wait`

- `docker container prune`
Expand Down
1 change: 1 addition & 0 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ var containerCommand = &cli.Command{
portCommand,
rmCommand,
stopCommand,
startCommand,
killCommand,
pauseCommand,
unpauseCommand,
Expand Down
7 changes: 3 additions & 4 deletions kill.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func killAction(clicontext *cli.Context) error {
walker := &containerwalker.ContainerWalker{
Client: client,
OnFound: func(ctx context.Context, found containerwalker.Found) error {
if err := killContainer(ctx, clicontext, found.Container, signal); err != nil {
if err := killContainer(ctx, found.Container, signal); err != nil {
if errdefs.IsNotFound(err) {
fmt.Fprintf(clicontext.App.ErrWriter, "Error response from daemon: Cannot kill container: %s: No such container: %s\n", found.Req, found.Req)
os.Exit(1)
Expand All @@ -94,7 +94,7 @@ func killAction(clicontext *cli.Context) error {
return nil
}

func killContainer(ctx context.Context, clicontext *cli.Context, container containerd.Container, signal syscall.Signal) error {
func killContainer(ctx context.Context, container containerd.Container, signal syscall.Signal) error {
task, err := container.Task(ctx, cio.Load)
if err != nil {
return err
Expand All @@ -109,8 +109,7 @@ func killContainer(ctx context.Context, clicontext *cli.Context, container conta

switch status.Status {
case containerd.Created, containerd.Stopped:
fmt.Fprintf(clicontext.App.ErrWriter, "Error response from daemon: Cannot kill container: %s: Container %s is not running\n", container.ID(), container.ID())
os.Exit(1)
return errors.Errorf("cannot kill container: %s: Container %s is not running\n", container.ID(), container.ID())
case containerd.Paused, containerd.Pausing:
paused = true
default:
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ func newApp() *cli.App {
logsCommand,
portCommand,
stopCommand,
startCommand,
killCommand,
rmCommand,
pauseCommand,
Expand Down
3 changes: 3 additions & 0 deletions pkg/labels/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,7 @@ const (

// Ports is a JSON-marshalled string of []gocni.PortMapping .
Ports = Prefix + "ports"

// LogURI is the log URI
LogURI = Prefix + "log-uri"
)
7 changes: 5 additions & 2 deletions run.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ func runAction(clicontext *cli.Context) error {
return err
}
}
ilOpt, err := withInternalLabels(ns, name, hostname, stateDir, clicontext.StringSlice("network"), ports)
ilOpt, err := withInternalLabels(ns, name, hostname, stateDir, clicontext.StringSlice("network"), ports, logURI)
if err != nil {
return err
}
Expand Down Expand Up @@ -689,7 +689,7 @@ func withContainerLabels(clicontext *cli.Context) ([]containerd.NewContainerOpts
return []containerd.NewContainerOpts{o}, nil
}

func withInternalLabels(ns, name, hostname, containerStateDir string, networks []string, ports []gocni.PortMapping) (containerd.NewContainerOpts, error) {
func withInternalLabels(ns, name, hostname, containerStateDir string, networks []string, ports []gocni.PortMapping, logURI string) (containerd.NewContainerOpts, error) {
m := make(map[string]string)
m[labels.Namespace] = ns
if name != "" {
Expand All @@ -709,6 +709,9 @@ func withInternalLabels(ns, name, hostname, containerStateDir string, networks [
}
m[labels.Ports] = string(portsJSON)
}
if logURI != "" {
m[labels.LogURI] = logURI
}
return containerd.WithAdditionalContainerLabels(m), nil
}

Expand Down
5 changes: 4 additions & 1 deletion run_network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,11 @@ func httpGet(urlStr string, attempts int) (*http.Response, error) {
if attempts < 1 {
return nil, errdefs.ErrInvalidArgument
}
client := &http.Client{
Timeout: 3 * time.Second,
}
for i := 0; i < attempts; i++ {
resp, err = http.Get(urlStr)
resp, err = client.Get(urlStr)
if err == nil {
return resp, nil
}
Expand Down
100 changes: 100 additions & 0 deletions start.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
Copyright (C) nerdctl authors.
Copyright (C) containerd authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"context"
"fmt"
"net/url"
"syscall"

"github.com/AkihiroSuda/nerdctl/pkg/idutil/containerwalker"
"github.com/AkihiroSuda/nerdctl/pkg/labels"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)

var startCommand = &cli.Command{
Name: "start",
Usage: "Start one or more running containers",
ArgsUsage: "[flags] CONTAINER [CONTAINER, ...]",
Action: startAction,
}

func startAction(clicontext *cli.Context) error {
if clicontext.NArg() == 0 {
return errors.Errorf("requires at least 1 argument")
}

client, ctx, cancel, err := newClient(clicontext)
if err != nil {
return err
}
defer cancel()

walker := &containerwalker.ContainerWalker{
Client: client,
OnFound: func(ctx context.Context, found containerwalker.Found) error {
if err := startContainer(ctx, found.Container); err != nil {
return err
}
_, err := fmt.Fprintf(clicontext.App.Writer, "%s\n", found.Req)
return err
},
}
for _, req := range clicontext.Args().Slice() {
n, err := walker.Walk(ctx, req)
if err != nil {
return err
} else if n == 0 {
return errors.Errorf("no such container %s", req)
}
}
return nil
}

func startContainer(ctx context.Context, container containerd.Container) error {
lab, err := container.Labels(ctx)
if err != nil {
return err
}
taskCIO := cio.NullIO
if logURIStr := lab[labels.LogURI]; logURIStr != "" {
logURI, err := url.Parse(logURIStr)
if err != nil {
return err
}
taskCIO = cio.LogURI(logURI)
}
if err = killContainer(ctx, container, syscall.SIGKILL); err != nil {
logrus.WithError(err).Debug("failed to kill container (negligible in most case)")
}
if oldTask, err := container.Task(ctx, nil); err == nil {
if _, err := oldTask.Delete(ctx); err != nil {
logrus.WithError(err).Debug("failed to delete old task")
}
}
task, err := container.NewTask(ctx, taskCIO)
if err != nil {
return err
}
return task.Start(ctx)
}
69 changes: 69 additions & 0 deletions stop_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
Copyright (C) nerdctl authors.
Copyright (C) containerd authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"fmt"
"io/ioutil"
"strings"
"testing"

"github.com/AkihiroSuda/nerdctl/pkg/testutil"
"github.com/pkg/errors"
"gotest.tools/v3/assert"
)

func TestStopStart(t *testing.T) {
const (
hostPort = 8080
testContainerName = "nerdctl-test-stop-start-nginx"
)
base := testutil.NewBase(t)
defer base.Cmd("rm", "-f", testContainerName).Run()

base.Cmd("run", "-d",
"--restart=no",
"--name", testContainerName,
"-p", fmt.Sprintf("127.0.0.1:%d:80", hostPort),
testutil.NginxAlpineImage).AssertOK()

check := func(httpGetRetry int) error {
resp, err := httpGet(fmt.Sprintf("http://127.0.0.1:%d", hostPort), httpGetRetry)
if err != nil {
return err
}
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if !strings.Contains(string(respBody), testutil.NginxAlpineIndexHTMLSnippet) {
return errors.Errorf("expected contain %q, got %q",
testutil.NginxAlpineIndexHTMLSnippet, string(respBody))
}
return nil
}

assert.NilError(t, check(30))
base.Cmd("stop", testContainerName).AssertOK()
base.Cmd("exec", testContainerName, "ps").AssertFail()
if check(1) == nil {
t.Fatal("expected to get an error")
}
base.Cmd("start", testContainerName).AssertOK()
assert.NilError(t, check(30))
}