list.go#Action
Action: func(context *cli.Context) error {
if err := checkArgs(context, 0, exactArgs); err != nil {
return err
}
// ********************************** NOTICE ********************************** //
s, err := getContainers(context)
// ********************************** NOTICE ********************************** //
if err != nil {
return err
}
if context.Bool("quiet") {
for _, item := range s {
fmt.Println(item.ID)
}
return nil
}
switch context.String("format") {
case "table":
w := tabwriter.NewWriter(os.Stdout, 12, 1, 3, ' ', 0)
fmt.Fprint(w, "ID\tPID\tSTATUS\tBUNDLE\tCREATED\tOWNER\n")
for _, item := range s {
fmt.Fprintf(w, "%s\t%d\t%s\t%s\t%s\t%s\n",
item.ID,
item.InitProcessPid,
item.Status,
item.Bundle,
item.Created.Format(time.RFC3339Nano),
item.Owner)
}
if err := w.Flush(); err != nil {
return err
}
case "json":
if err := json.NewEncoder(os.Stdout).Encode(s); err != nil {
return err
}
default:
return fmt.Errorf("invalid format option")
}
return nil
},
1) list.go#getContainers
func getContainers(context *cli.Context) ([]containerState, error) {
factory, err := loadFactory(context)
if err != nil {
return nil, err
}
root := context.GlobalString("root")
absRoot, err := filepath.Abs(root)
if err != nil {
return nil, err
}
list, err := ioutil.ReadDir(absRoot)
if err != nil {
fatal(err)
}
var s []containerState
for _, item := range list {
if item.IsDir() {
// This cast is safe on Linux.
stat := item.Sys().(*syscall.Stat_t)
owner, err := user.LookupUid(int(stat.Uid))
if err != nil {
owner.Name = fmt.Sprintf("#%d", stat.Uid)
}
// ********************************** NOTICE ******************************** //
container, err := factory.Load(item.Name())
// ********************************** NOTICE ******************************** //
if err != nil {
fmt.Fprintf(os.Stderr, "load container %s: %v\n", item.Name(), err)
continue
}
containerStatus, err := container.Status()
if err != nil {
fmt.Fprintf(os.Stderr, "status for %s: %v\n", item.Name(), err)
continue
}
state, err := container.State()
if err != nil {
fmt.Fprintf(os.Stderr, "state for %s: %v\n", item.Name(), err)
continue
}
pid := state.BaseState.InitProcessPid
if containerStatus == libcontainer.Stopped {
pid = 0
}
bundle, annotations := utils.Annotations(state.Config.Labels)
s = append(s, containerState{
Version: state.BaseState.Config.Version,
ID: state.BaseState.ID,
InitProcessPid: pid,
Status: containerStatus.String(),
Bundle: bundle,
Rootfs: state.BaseState.Config.Rootfs,
Created: state.BaseState.Created,
Annotations: annotations,
Owner: owner.Name,
})
}
}
return s, nil
}