aboutsummaryrefslogtreecommitdiff
path: root/pkg/api/handlers/utils/pods.go
blob: 0bb818c1cdb5414649753f9855cb23407b68c9e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package utils

import (
	"net/http"

	"github.com/containers/libpod/libpod"
	lpfilters "github.com/containers/libpod/libpod/filters"
	"github.com/containers/libpod/pkg/domain/entities"
	"github.com/gorilla/schema"
)

func GetPods(w http.ResponseWriter, r *http.Request) ([]*entities.ListPodsReport, error) {
	var (
		pods    []*libpod.Pod
		filters []libpod.PodFilter
	)
	runtime := r.Context().Value("runtime").(*libpod.Runtime)
	decoder := r.Context().Value("decoder").(*schema.Decoder)

	query := struct {
		All     bool
		Filters map[string][]string `schema:"filters"`
		Digests bool
	}{}

	if err := decoder.Decode(&query, r.URL.Query()); err != nil {
		return nil, err
	}
	if _, found := r.URL.Query()["digests"]; found && query.Digests {
		UnSupportedParameter("digests")
	}

	for k, v := range query.Filters {
		for _, filter := range v {
			f, err := lpfilters.GeneratePodFilterFunc(k, filter)
			if err != nil {
				return nil, err
			}
			filters = append(filters, f)
		}
	}
	pods, err := runtime.Pods(filters...)
	if err != nil {
		return nil, err
	}

	if len(pods) == 0 {
		return nil, nil
	}

	lps := make([]*entities.ListPodsReport, 0, len(pods))
	for _, pod := range pods {
		status, err := pod.GetPodStatus()
		if err != nil {
			return nil, err
		}
		ctrs, err := pod.AllContainers()
		if err != nil {
			return nil, err
		}
		infraID, err := pod.InfraContainerID()
		if err != nil {
			return nil, err
		}
		lp := entities.ListPodsReport{
			Cgroup:    pod.CgroupParent(),
			Created:   pod.CreatedTime(),
			Id:        pod.ID(),
			Name:      pod.Name(),
			Namespace: pod.Namespace(),
			Status:    status,
			InfraId:   infraID,
			Labels:    pod.Labels(),
		}
		for _, ctr := range ctrs {
			state, err := ctr.State()
			if err != nil {
				return nil, err
			}
			lp.Containers = append(lp.Containers, &entities.ListPodContainer{
				Id:     ctr.ID(),
				Names:  ctr.Name(),
				Status: state.String(),
			})
		}
		lps = append(lps, &lp)
	}
	return lps, nil
}