podman

Форк
0
/
runtime_pod.go 
189 строк · 4.7 Кб
1
//go:build !remote
2

3
package libpod
4

5
import (
6
	"context"
7
	"errors"
8
	"fmt"
9
	"time"
10

11
	"github.com/containers/podman/v5/libpod/define"
12
	"golang.org/x/exp/slices"
13
)
14

15
// Contains the public Runtime API for pods
16

17
// A PodCreateOption is a functional option which alters the Pod created by
18
// NewPod
19
type PodCreateOption func(*Pod) error
20

21
// PodFilter is a function to determine whether a pod is included in command
22
// output. Pods to be outputted are tested using the function. A true return
23
// will include the pod, a false return will exclude it.
24
type PodFilter func(*Pod) bool
25

26
// RemovePod removes a pod
27
// If removeCtrs is specified, containers will be removed
28
// Otherwise, a pod that is not empty will return an error and not be removed
29
// If force is specified with removeCtrs, all containers will be stopped before
30
// being removed
31
// Otherwise, the pod will not be removed if any containers are running
32
func (r *Runtime) RemovePod(ctx context.Context, p *Pod, removeCtrs, force bool, timeout *uint) (map[string]error, error) {
33
	if !r.valid {
34
		return nil, define.ErrRuntimeStopped
35
	}
36

37
	if !p.valid {
38
		if ok, _ := r.state.HasPod(p.ID()); !ok {
39
			// Pod probably already removed
40
			// Or was never in the runtime to begin with
41
			return make(map[string]error), nil
42
		}
43
	}
44

45
	p.lock.Lock()
46
	defer p.lock.Unlock()
47

48
	return r.removePod(ctx, p, removeCtrs, force, timeout)
49
}
50

51
// GetPod retrieves a pod by its ID
52
func (r *Runtime) GetPod(id string) (*Pod, error) {
53
	if !r.valid {
54
		return nil, define.ErrRuntimeStopped
55
	}
56

57
	return r.state.Pod(id)
58
}
59

60
// HasPod checks to see if a pod with the given ID exists
61
func (r *Runtime) HasPod(id string) (bool, error) {
62
	if !r.valid {
63
		return false, define.ErrRuntimeStopped
64
	}
65

66
	return r.state.HasPod(id)
67
}
68

69
// LookupPod retrieves a pod by its name or a partial ID
70
// If a partial ID is not unique, an error will be returned
71
func (r *Runtime) LookupPod(idOrName string) (*Pod, error) {
72
	if !r.valid {
73
		return nil, define.ErrRuntimeStopped
74
	}
75

76
	return r.state.LookupPod(idOrName)
77
}
78

79
// Pods retrieves all pods
80
// Filters can be provided which will determine which pods are included in the
81
// output. Multiple filters are handled by ANDing their output, so only pods
82
// matching all filters are returned
83
func (r *Runtime) Pods(filters ...PodFilter) ([]*Pod, error) {
84
	pods, err := r.GetAllPods()
85
	if err != nil {
86
		return nil, err
87
	}
88
	podsFiltered := make([]*Pod, 0, len(pods))
89
	for _, pod := range pods {
90
		include := true
91
		for _, filter := range filters {
92
			include = include && filter(pod)
93
		}
94

95
		if include {
96
			podsFiltered = append(podsFiltered, pod)
97
		}
98
	}
99

100
	return podsFiltered, nil
101
}
102

103
// GetAllPods retrieves all pods
104
func (r *Runtime) GetAllPods() ([]*Pod, error) {
105
	if !r.valid {
106
		return nil, define.ErrRuntimeStopped
107
	}
108

109
	return r.state.AllPods()
110
}
111

112
// GetLatestPod returns a pod object of the latest created pod.
113
func (r *Runtime) GetLatestPod() (*Pod, error) {
114
	lastCreatedIndex := -1
115
	var lastCreatedTime time.Time
116
	pods, err := r.GetAllPods()
117
	if err != nil {
118
		return nil, fmt.Errorf("unable to get all pods: %w", err)
119
	}
120
	if len(pods) == 0 {
121
		return nil, define.ErrNoSuchPod
122
	}
123
	for podIndex, pod := range pods {
124
		createdTime := pod.config.CreatedTime
125
		if createdTime.After(lastCreatedTime) {
126
			lastCreatedTime = createdTime
127
			lastCreatedIndex = podIndex
128
		}
129
	}
130
	return pods[lastCreatedIndex], nil
131
}
132

133
// GetRunningPods returns an array of running pods
134
func (r *Runtime) GetRunningPods() ([]*Pod, error) {
135
	var (
136
		pods        []string
137
		runningPods []*Pod
138
	)
139
	if !r.valid {
140
		return nil, define.ErrRuntimeStopped
141
	}
142
	containers, err := r.GetRunningContainers()
143
	if err != nil {
144
		return nil, err
145
	}
146
	// Assemble running pods
147
	for _, c := range containers {
148
		if !slices.Contains(pods, c.PodID()) {
149
			pods = append(pods, c.PodID())
150
			pod, err := r.GetPod(c.PodID())
151
			if err != nil {
152
				if errors.Is(err, define.ErrPodRemoved) || errors.Is(err, define.ErrNoSuchPod) {
153
					continue
154
				}
155
				return nil, err
156
			}
157
			runningPods = append(runningPods, pod)
158
		}
159
	}
160
	return runningPods, nil
161
}
162

163
// PrunePods removes unused pods and their containers from local storage.
164
func (r *Runtime) PrunePods(ctx context.Context) (map[string]error, error) {
165
	response := make(map[string]error)
166
	states := []string{define.PodStateStopped, define.PodStateExited}
167
	filterFunc := func(p *Pod) bool {
168
		state, _ := p.GetPodStatus()
169
		for _, status := range states {
170
			if state == status {
171
				return true
172
			}
173
		}
174
		return false
175
	}
176
	pods, err := r.Pods(filterFunc)
177
	if err != nil {
178
		return nil, err
179
	}
180
	if len(pods) < 1 {
181
		return response, nil
182
	}
183
	for _, pod := range pods {
184
		var timeout *uint
185
		_, err := r.removePod(context.TODO(), pod, true, false, timeout)
186
		response[pod.ID()] = err
187
	}
188
	return response, nil
189
}
190

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.