Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: add "pouch rm" #214

Merged
merged 1 commit into from
Dec 8, 2017
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion apis/server/container_bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,27 @@ import (
"time"

"github.com/alibaba/pouch/apis/types"
"github.com/alibaba/pouch/daemon/mgr"
"github.com/alibaba/pouch/pkg/httputils"

"github.com/gorilla/mux"
)

// TODO
func (s *Server) removeContainers(ctx context.Context, resp http.ResponseWriter, req *http.Request) error {
name := mux.Vars(req)["name"]

option := &mgr.ContainerRemoveOption{
Force: httputils.BoolValue(req, "force"),
// TODO Volume and Link will be supported in the future.
Volume: httputils.BoolValue(req, "v"),
Link: httputils.BoolValue(req, "link"),
}

if err := s.ContainerMgr.Remove(ctx, name, option); err != nil {
return err
}

resp.WriteHeader(http.StatusNoContent)
return nil
}

Expand Down
19 changes: 18 additions & 1 deletion apis/swagger.yml
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,24 @@ paths:
schema:
$ref: "#/definitions/Error"
tags: ["Container"]

/containers/{name}:
delete:
summary: "Remove one container"
operationId: "ContainerRemove"
parameters:
- name: "name"
in: "path"
required: true
description: "ID or name of the container"
type: "string"
responses:
204:
description: "no error"
500:
description: "server error"
schema:
$ref: "#/definitions/Error"
tags: ["Container"]
/volumes:
get:
summary: "List volumes"
Expand Down
1 change: 1 addition & 0 deletions cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func main() {
cli.AddCommand(base, &StartCommand{})
cli.AddCommand(base, &StopCommand{})
cli.AddCommand(base, &PsCommand{})
cli.AddCommand(base, &RmCommand{})
cli.AddCommand(base, &ExecCommand{})
cli.AddCommand(base, &VersionCommand{})
cli.AddCommand(base, &ImageCommand{})
Expand Down
64 changes: 64 additions & 0 deletions cli/rm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package main

import (
"fmt"

"github.com/spf13/cobra"
)

var rmDescription = `
Remove a container object in Pouchd.
If a container be stopped or created, you can remove it.
If the container be running, you can also remove it with flag force.
When the container be removed, the all resource of the container will
be released.
`

// RmCommand is used to implement 'rm' command.
type RmCommand struct {
baseCommand
force bool
}

// Init initializes RmCommand command.
func (r *RmCommand) Init(c *Cli) {
r.cli = c
r.cmd = &cobra.Command{
Use: "rm container",
Short: "Remove one or more containers",
Long: rmDescription,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return r.runRm(args)
},
Example: rmExample(),
}
r.addFlags()
}

// addFlags adds flags for specific command.
func (r *RmCommand) addFlags() {
r.cmd.Flags().BoolVarP(&r.force, "force", "f", false, "if the container is running, force to remove it")
}

// runRm is the entry of RmCommand command.
func (r *RmCommand) runRm(args []string) error {
apiClient := r.cli.Client()

for _, name := range args {
if err := apiClient.ContainerRemove(name, r.force); err != nil {
return fmt.Errorf("failed to remove container: %v", err)
}
fmt.Printf("%s\n", name)
}

return nil
}

func rmExample() string {
return `$ pouch rm 5d3152
5d3152

$ pouch rm -f 493028
493028`
}
17 changes: 16 additions & 1 deletion client/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,29 @@ func (client *APIClient) ContainerStart(name, detachKeys string) error {
return err
}

// ContainerStop stops a container
// ContainerStop stops a container.
func (client *APIClient) ContainerStop(name string) error {
resp, err := client.post("/containers/"+name+"/stop", nil, nil)
ensureCloseReader(resp)

return err
}

// ContainerRemove removes a container.
func (client *APIClient) ContainerRemove(name string, force bool) error {
q := url.Values{}
if force {
q.Set("force", "true")
}

resp, err := client.delete("/containers/"+name, q)
if err != nil {
return err
}
ensureCloseReader(resp)
return nil
}

// ContainerList returns the list of containers.
func (client *APIClient) ContainerList() ([]*types.Container, error) {
resp, err := client.get("/containers/json", nil)
Expand Down
42 changes: 40 additions & 2 deletions daemon/mgr/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,38 @@ func (mgr *ContainerManager) Restore(ctx context.Context) error {
}

// Remove removes a container, it may be running or stopped and so on.
// TODO
func (mgr *ContainerManager) Remove(ctx context.Context, name string, option *ContainerRemoveOption) error {
c, err := mgr.container(name)
Copy link
Collaborator

@allencloud allencloud Dec 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the future, I think we need to classify a StatusNotFound code here, since we may not find container by input name.
We need to do this, in follow-up pull requests.

if err != nil {
return err
}
c.Lock()
defer c.Unlock()

if !c.IsStopped() && !c.IsCreated() && !option.Force {
return fmt.Errorf("container: %s is not stopped, can't remove it without flag force", c.ID())
}

// if the container is running, force to stop it.
if c.IsRunning() && option.Force {
if _, err := mgr.Client.DestroyContainer(ctx, c.ID()); err != nil {
if cerr, ok := err.(ctrd.Error); !ok || cerr != ctrd.ErrContainerNotfound {
return errors.Wrapf(err, "failed to remove container: %s", c.ID())
}
}
}

// remove name
mgr.NameToID.Remove(c.Name())

// remove meta data
if err := mgr.Store.Remove(c.meta.Key()); err != nil {
logrus.Errorf("failed to remove container: %s meta store", c.ID())
}

// remove container cache
mgr.cache.Remove(c.ID())

return nil
}

Expand Down Expand Up @@ -389,7 +419,15 @@ func (mgr *ContainerManager) List(ctx context.Context) ([]*types.ContainerInfo,

// Get the detailed information of container
func (mgr *ContainerManager) Get(name string) (*types.ContainerInfo, error) {
return mgr.containerInfo(name)
c, err := mgr.container(name)
if err != nil {
return nil, err
}

c.Lock()
defer c.Unlock()

return c.meta, nil
}

// Rename renames a container
Expand Down
10 changes: 10 additions & 0 deletions daemon/mgr/container_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ func (c *Container) ID() string {
return c.meta.ID
}

// Name returns container's name.
func (c *Container) Name() string {
return c.meta.Name
}

// IsRunning returns container is running or not.
func (c *Container) IsRunning() bool {
return c.meta.Status == types.RUNNING
Expand All @@ -42,6 +47,11 @@ func (c *Container) IsStopped() bool {
return c.meta.Status == types.STOPPED
}

// IsCreated returns container is created or not.
func (c *Container) IsCreated() bool {
return c.meta.Status == types.CREATED
}

// Write writes container's meta data into meta store.
func (c *Container) Write(store *meta.Store) error {
return store.Put(c.meta)
Expand Down
12 changes: 12 additions & 0 deletions pkg/httputils/http_utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package httputils

import (
"net/http"
"strings"
)

// BoolValue transforms a form value in different formats into a boolean type.
func BoolValue(r *http.Request, k string) bool {
s := strings.ToLower(strings.TrimSpace(r.FormValue(k)))
return !(s == "" || s == "0" || s == "no" || s == "false" || s == "none")
}