package docker import ( "context" "sort" "io" "github.com/cuigh/swirl/model" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/client" ) // TaskList return all running tasks of a service or a node. func TaskList(service, node string) (infos []*model.TaskInfo, err error) { err = mgr.Do(func(ctx context.Context, cli *client.Client) (err error) { var ( tasks []swarm.Task ) opts := types.TaskListOptions{ Filters: filters.NewArgs(), } if service != "" { opts.Filters.Add("service", service) } if node != "" { opts.Filters.Add("node", node) } tasks, err = cli.TaskList(ctx, opts) if err == nil && len(tasks) > 0 { sort.Slice(tasks, func(i, j int) bool { return tasks[i].UpdatedAt.After(tasks[j].UpdatedAt) }) nodes := make(map[string]string) for _, t := range tasks { if _, ok := nodes[t.NodeID]; !ok { if n, _, e := cli.NodeInspectWithRaw(ctx, t.NodeID); e == nil { nodes[t.NodeID] = n.Description.Hostname } else { nodes[t.NodeID] = "" //mgr.Logger().Warnf("Node %s of task %s can't be load: %s", t.NodeID, t.ID, e) } } } infos = make([]*model.TaskInfo, len(tasks)) for i, t := range tasks { infos[i] = model.NewTaskInfo(t, nodes[t.NodeID]) } } return }) return } // TaskInspect return detail information of a task. func TaskInspect(id string) (task swarm.Task, raw []byte, err error) { err = mgr.Do(func(ctx context.Context, cli *client.Client) (err error) { task, raw, err = cli.TaskInspectWithRaw(ctx, id) return }) return } // TaskLogs returns the logs generated by a task in an io.ReadCloser. // It's up to the caller to close the stream. func TaskLogs(id string) (rc io.ReadCloser, err error) { err = mgr.Do(func(ctx context.Context, cli *client.Client) (err error) { opts := types.ContainerLogsOptions{} rc, err = cli.TaskLogs(ctx, id, opts) return }) return }