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 --format option for pouch ps #2844

Closed
Closed
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
10 changes: 10 additions & 0 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"strconv"
"text/tabwriter"
"text/template"
Copy link
Collaborator

Choose a reason for hiding this comment

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

There will be a merge conflict, please handle and rebase it!

"time"

"github.com/alibaba/pouch/client"
Expand Down Expand Up @@ -159,6 +160,15 @@ func (c *Cli) Print(obj interface{}) {
display.Flush()
}

// FormatDisplay use to format output with options
func (c *Cli) FormatDisplay(format string, tmpl *template.Template, container interface{}, w *tabwriter.Writer) error {
tmpl, err := tmpl.Parse(format)
if err != nil {
return err
}
return tmpl.Execute(w, container)
}

// ExitError defines exit error produce by cli commands.
type ExitError struct {
Code int
Expand Down
70 changes: 70 additions & 0 deletions cli/formatter/container.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package formatter

import (
"fmt"
"time"

"github.com/alibaba/pouch/apis/types"
"github.com/alibaba/pouch/pkg/utils"
)

// ContainerHeader is the map to show container head
var ContainerHeader = map[string]string{
"Names": "Name",
"ID": "ID",
"Status": "Status",
"RunningFor": "Created",
"Image": "Image",
"Runtime": "Runtime",
"Command": "Command",
"ImageID": "ImageID",
"Labels": "Labels",
"Mounts": "Mounts",
"State": "State",
"Ports": "Ports",
"Size": "Size",
"LocalVolumes": "LocalVolumes",
"Networks": "Networks",
"CreatedAt": "CreatedAt",
}

// ContainerContext is the map to show container context detail
type ContainerContext map[string]string

// NewContainerContext is to generate a ContainerContext to be show
func NewContainerContext(c *types.Container, flagNoTrunc bool) (containerContext ContainerContext, err error) {
id := c.ID[:6]
if flagNoTrunc {
id = c.ID
}
runningFor, err := utils.FormatTimeInterval(c.Created)
Copy link
Collaborator

Choose a reason for hiding this comment

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

utils.FormatTimeInterval function have an extra new param, please fix it!

if err != nil {
return nil, err
}
createdAt := time.Unix(0, c.Created).String()
networks := c.HostConfig.NetworkMode
ports := PortBindingsToString(c.HostConfig.PortBindings)
size := SizeToString(c.SizeRw, c.SizeRootFs)
labels := LabelsToString(c.Labels)
mount := MountPointToString(c.Mounts)
localVolume := LocalVolumes(c.Mounts)
containerContext = ContainerContext{
"Names": c.Names[0],
"ID": id,
"Status": c.Status,
"RunningFor": fmt.Sprintf("%s ago", runningFor),
"Image": c.Image,
"Runtime": c.HostConfig.Runtime,
"Command": c.Command,
"ImageID": c.ImageID,
"Labels": labels,
"Mounts": mount,
"State": c.State,
"Ports": ports,
"Size": size,
"LocalVolumes": localVolume,
"Networks": networks,
"CreatedAt": createdAt,
}
return containerContext, nil
}
100 changes: 100 additions & 0 deletions cli/formatter/container_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package formatter

import (
"testing"

"github.com/alibaba/pouch/apis/types"

"github.com/stretchr/testify/assert"
)

func TestNewContainerContext(t *testing.T) {
type TestCase struct {
container *types.Container
flagNoTrunc bool
expected ContainerContext
}

testCases := []TestCase{
{
container: &types.Container{
Command: "bash",
Created: 8392772900000,
HostConfig: &types.HostConfig{Runtime: "runc", PortBindings: types.PortMap{"80/tcp": []types.PortBinding{{HostIP: "127.0.0.1", HostPort: "80"}, {HostIP: "127.0.0.1", HostPort: "88"}}}, NetworkMode: "bridge"},
ID: "abcdelj8937",
Image: "Image123",
ImageID: "234567890",
Labels: map[string]string{"a": "b", "c": "d"},
Names: []string{"nameA", "nameB"},
State: "StateA",
Status: "StatusB",
Mounts: []types.MountPoint{
{Source: "/root/code", Driver: "local"},
{Source: "/test"},
},
SizeRw: 10,
SizeRootFs: 100,
},
flagNoTrunc: false,
expected: ContainerContext{
"Names": "nameA",
"ID": "abcdel",
"Status": "StatusB",
"RunningFor": "49 years" + " ago",
"Image": "Image123",
"Runtime": "runc",
"Command": "bash",
"ImageID": "234567890",
"Labels": "a = b;c = d;",
"Mounts": "/root/code;/test;",
"State": "StateA",
"Ports": "80/tcp->127.0.0.1:80;80/tcp->127.0.0.1:88;",
"Size": "10B (virtual 100B)",
"LocalVolumes": "1",
"Networks": "bridge",
"CreatedAt": "1970-01-01 02:19:52.7729 +0000 UTC",
},
},
{
container: &types.Container{
Command: "shell",
Created: 997349794700000,
HostConfig: &types.HostConfig{Runtime: "runv"},
ID: "1234567890",
Image: "Image456",
ImageID: "abcdefg",
Labels: map[string]string{},
Names: []string{"nameB", "nameA"},
State: "StateB",
Status: "StatusA",
Mounts: []types.MountPoint{
{Source: "/root/code"},
{Source: "/test"},
},
},
flagNoTrunc: true,
expected: ContainerContext{
"Names": "nameB",
"ID": "1234567890",
"Status": "StatusA",
"RunningFor": "49 years" + " ago",
"Image": "Image456",
"Runtime": "runv",
"Command": "shell",
"ImageID": "abcdefg",
"Labels": "",
"Mounts": "/root/code;/test;",
"State": "StateB",
"Ports": "",
"Size": "0B",
"LocalVolumes": "0",
"Networks": "",
"CreatedAt": "1970-01-12 13:02:29.7947 +0000 UTC",
},
},
}
for _, testCase := range testCases {
result, _ := NewContainerContext(testCase.container, testCase.flagNoTrunc)
assert.Equal(t, testCase.expected, result)
}
}
101 changes: 101 additions & 0 deletions cli/formatter/formatter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package formatter

import (
"fmt"
"sort"
"strings"

"github.com/alibaba/pouch/apis/types"
units "github.com/docker/go-units"
)

// Format key to output
const (
TableFormat = "table"
ZYecho marked this conversation as resolved.
Show resolved Hide resolved
RawFormat = "raw"
)

// IsTable to verify if table or raw
func IsTable(format string) bool {
return strings.HasPrefix(format, TableFormat)
}

// PreFormat is to format the format option
func PreFormat(format string) string {
if IsTable(format) {
format = format[len(TableFormat):]
// cut the space
format = strings.Trim(format, " ")
// input by cmd of "\t" is "\\t"
replace := strings.NewReplacer(`\t`, "\t", `\n`, "\n")
ZYecho marked this conversation as resolved.
Show resolved Hide resolved
format = replace.Replace(format)

if format[len(format)-1:] != "\n" {
format += "\n"
}
} else {
format = "Name:{{.Names}}\nID:{{.ID}}\nStatus:{{.Status}}\nCreated:{{.RunningFor}}\nImage:{{.Image}}\nRuntime:{{.Runtime}}\n\n"
}
return format
}

// LabelsToString is to transform the labels from map to string
func LabelsToString(labels map[string]string) string {
var labelstring string
sortedkeys := make([]string, 0)
for key := range labels {
sortedkeys = append(sortedkeys, key)
}
sort.Strings(sortedkeys)
for _, key := range sortedkeys {
labelstring += fmt.Sprintf("%s = %s;", key, labels[key])
}
return labelstring
}

// MountPointToString is to transform the MountPoint from array to string
func MountPointToString(mount []types.MountPoint) string {
aohang111 marked this conversation as resolved.
Show resolved Hide resolved
var mountstring string
for _, value := range mount {
mountstring += fmt.Sprintf("%s;", value.Source)
}
return mountstring
}

// PortBindingsToString is to transform the portbindings from map to string
func PortBindingsToString(portMap types.PortMap) string {
var portBindings string
sortedkeys := make([]string, 0)
for key := range portMap {
sortedkeys = append(sortedkeys, key)
}
for _, key := range sortedkeys {
for _, ipPort := range portMap[key] {
portBindings += fmt.Sprintf("%s->%s:%s;", key, ipPort.HostIP, ipPort.HostPort)
}
}
return portBindings
}

// SizeToString is to get the size related output
func SizeToString(sizeRw int64, sizeRootFs int64) string {
var strResult string
sRw := units.HumanSizeWithPrecision(float64(sizeRw), 3)
sRFs := units.HumanSizeWithPrecision(float64(sizeRootFs), 3)
strResult = sRw
if sizeRootFs > 0 {
strResult = fmt.Sprintf("%s (virtual %s)", sRw, sRFs)
}
return strResult
}

// LocalVolumes is get the count of local volumes
func LocalVolumes(mount []types.MountPoint) string {
c := 0
for _, v := range mount {
if v.Driver == "local" {
c++
}
}
return fmt.Sprintf("%d", c)
}
Loading