Debian Codegraph @

ansible_collections/containers/podman/plugins/modules/podman_container_info.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2020 Red Hat
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import absolute_import, division, print_function
6
7 __metaclass__ = type
8
9
10 DOCUMENTATION = r"""
11 module: podman_container_info
12 author:
13 - Sagi Shnaidman (@podman)
14 - Emilien Macchi (@EmilienM)
15 short_description: Gather facts about containers using podman
16 notes:
17 - Podman may require elevated privileges in order to run properly.
18 description:
19 - Gather facts about containers using C(podman)
20 requirements:
21 - "Podman installed on host"
22 options:
23 name:
24 description:
25 - List of container names to gather facts about. If no name is given
26 return facts about all containers.
27 type: list
28 elements: str
29 executable:
30 description:
31 - Path to C(podman) executable if it is not in the C($PATH) on the
32 machine running C(podman)
33 default: 'podman'
34 type: str
35 """
36
37 EXAMPLES = r"""
38 - name: Gather facts for all containers
39 containers.podman.podman_container_info:
40
41 - name: Gather facts on a specific container
42 containers.podman.podman_container_info:
43 name: web1
44
45 - name: Gather facts on several containers
46 containers.podman.podman_container_info:
47 name:
48 - redis
49 - web1
50 """
51
52 RETURN = r"""
53 containers:
54 description: Facts from all or specified containers
55 returned: always
56 type: list
57 elements: dict
58 sample: [
59 {
60 "Id": "d38a8fcd61ab7e0754355e8fb3acc201e07770f3d1fd8fed36556941ac458ce",
61 "Created": "2024-08-14T00:04:33.127266655+03:00",
62 "Path": "/entrypoint.sh",
63 "Args": [
64 "/entrypoint.sh"
65 ],
66 "State": {
67 "OciVersion": "1.1.0+dev",
68 "Status": "running",
69 "Running": true,
70 "Paused": false,
71 "Restarting": false,
72 "OOMKilled": false,
73 "Dead": false,
74 "Pid": 2434164,
75 "ConmonPid": 2434162,
76 "ExitCode": 0,
77 "Error": "",
78 "StartedAt": "2024-08-14T00:04:33.237286439+03:00",
79 "FinishedAt": "0001-01-01T00:00:00Z",
80 "Health": {
81 "Status": "",
82 "FailingStreak": 0,
83 "Log": null
84 },
85 "CgroupPath": "/user.slice/user-1000.slice/[email protected]/user.slice/libpod-d38a....scope",
86 "CheckpointedAt": "0001-01-01T00:00:00Z",
87 "RestoredAt": "0001-01-01T00:00:00Z"
88 },
89 "Image": "fe2ba3a8ede60e5938e666b483c3a812ba902dac2303341930fbadc0482592b7",
90 "ImageDigest": "sha256:1222865ed7489298ee28414ddedb63a0c6405938c3a38adf21c8656d7f532271",
91 "ImageName": "registry/org/image:latest",
92 "Rootfs": "",
93 "Pod": "",
94 "ResolvConfPath": "/run/user/1000/containers/overlay-containers/d38a.../userdata/resolv.conf",
95 "HostnamePath": "/run/user/1000/containers/overlay-containers/d38a.../userdata/hostname",
96 "HostsPath": "/run/user/1000/containers/overlay-containers/d38a.../userdata/hosts",
97 "StaticDir": "/home/podman/.local/share/containers/storage/overlay-containers/d38a.../userdata",
98 "OCIConfigPath": "/home/podman/.local/share/containers/....json",
99 "OCIRuntime": "crun",
100 "ConmonPidFile": "/run/user/1000/containers/overlay-containers/d38a.../userdata/conmon.pid",
101 "PidFile": "/run/user/1000/containers/overlay-containers/d38a.../userdata/pidfile",
102 "Name": "costapp",
103 "RestartCount": 0,
104 "Driver": "overlay",
105 "MountLabel": "system_u:object_r:container_file_t:s0:c493,c986",
106 "ProcessLabel": "system_u:system_r:container_t:s0:c493,c986",
107 "AppArmorProfile": "",
108 "EffectiveCaps": [
109 "CAP_CHOWN",
110 "CAP_DAC_OVERRIDE",
111 "CAP_FOWNER",
112 "CAP_FSETID",
113 "CAP_KILL",
114 "CAP_NET_BIND_SERVICE",
115 "CAP_SETFCAP",
116 "CAP_SETGID",
117 "CAP_SETPCAP",
118 "CAP_SETUID",
119 "CAP_SYS_CHROOT"
120 ],
121 "BoundingCaps": [
122 "CAP_CHOWN",
123 "CAP_DAC_OVERRIDE",
124 "CAP_FOWNER",
125 "CAP_FSETID",
126 "CAP_KILL",
127 "CAP_NET_BIND_SERVICE",
128 "CAP_SETFCAP",
129 "CAP_SETGID",
130 "CAP_SETPCAP",
131 "CAP_SETUID",
132 "CAP_SYS_CHROOT"
133 ],
134 "ExecIDs": [],
135 "GraphDriver": {
136 "Name": "overlay",
137 "Data": {
138 "LowerDir": "/home/podman/.local/share/containers/storage/overlay/29e2.../diff:...",
139 "MergedDir": "/home/podman/.local/share/containers/storage/overlay/865909.../merged",
140 "UpperDir": "/home/podman/.local/share/containers/storage/overlay/865909.../diff",
141 "WorkDir": "/home/podman/.local/share/containers/storage/overlay/865909.../work"
142 }
143 },
144 "Mounts": [],
145 "Dependencies": [],
146 "NetworkSettings": {
147 "EndpointID": "",
148 "Gateway": "",
149 "IPAddress": "",
150 "IPPrefixLen": 0,
151 "IPv6Gateway": "",
152 "GlobalIPv6Address": "",
153 "GlobalIPv6PrefixLen": 0,
154 "MacAddress": "",
155 "Bridge": "",
156 "SandboxID": "",
157 "HairpinMode": false,
158 "LinkLocalIPv6Address": "",
159 "LinkLocalIPv6PrefixLen": 0,
160 "Ports": {
161 "80/tcp": [
162 {
163 "HostIp": "",
164 "HostPort": "8888"
165 }
166 ]
167 },
168 "SandboxKey": "/run/user/1000/netns/netns-2343321-795a-8289-14c0-77ee2556ebf1"
169 },
170 "Namespace": "",
171 "IsInfra": false,
172 "IsService": false,
173 "KubeExitCodePropagation": "invalid",
174 "lockNumber": 1417,
175 "Config": {
176 "Hostname": "444a8274863a",
177 "Domainname": "",
178 "User": "",
179 "AttachStdin": false,
180 "AttachStdout": false,
181 "AttachStderr": false,
182 "Tty": false,
183 "OpenStdin": false,
184 "StdinOnce": false,
185 "Env": [
186 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
187 "container=podman",
188 "HOME=/root",
189 "HOSTNAME=444a8274863a"
190 ],
191 "Cmd": null,
192 "Image": "registry/org/image:latest",
193 "Volumes": null,
194 "WorkingDir": "/",
195 "Entrypoint": "/entrypoint.sh",
196 "OnBuild": null,
197 "Labels": {
198 "io.buildah.version": "1.31.2"
199 },
200 "Annotations": {
201 "io.container.manager": "libpod",
202 "org.opencontainers.image.stopSignal": "15"
203 },
204 "StopSignal": 15,
205 "HealthcheckOnFailureAction": "none",
206 "CreateCommand": [
207 "podman",
208 "run",
209 "-d",
210 "--name",
211 "test",
212 "-p",
213 "8888:80",
214 "registry/org/image:latest"
215 ],
216 "Umask": "0022",
217 "Timeout": 0,
218 "StopTimeout": 10,
219 "Passwd": true,
220 "sdNotifyMode": "container"
221 },
222 "HostConfig": {
223 "Binds": [],
224 "CgroupManager": "systemd",
225 "CgroupMode": "private",
226 "ContainerIDFile": "",
227 "LogConfig": {
228 "Type": "journald",
229 "Config": null,
230 "Path": "",
231 "Tag": "",
232 "Size": "0B"
233 },
234 "NetworkMode": "slirp4netns",
235 "PortBindings": {
236 "80/tcp": [
237 {
238 "HostIp": "",
239 "HostPort": "8888"
240 }
241 ]
242 },
243 "RestartPolicy": {
244 "Name": "",
245 "MaximumRetryCount": 0
246 },
247 "AutoRemove": false,
248 "VolumeDriver": "",
249 "VolumesFrom": null,
250 "CapAdd": [],
251 "CapDrop": [],
252 "Dns": [],
253 "DnsOptions": [],
254 "DnsSearch": [],
255 "ExtraHosts": [],
256 "GroupAdd": [],
257 "IpcMode": "shareable",
258 "Cgroup": "",
259 "Cgroups": "default",
260 "Links": null,
261 "OomScoreAdj": 0,
262 "PidMode": "private",
263 "Privileged": false,
264 "PublishAllPorts": false,
265 "ReadonlyRootfs": false,
266 "SecurityOpt": [],
267 "Tmpfs": {},
268 "UTSMode": "private",
269 "UsernsMode": "",
270 "ShmSize": 65536000,
271 "Runtime": "oci",
272 "ConsoleSize": [
273 0,
274 0
275 ],
276 "Isolation": "",
277 "CpuShares": 0,
278 "Memory": 0,
279 "NanoCpus": 0,
280 "CgroupParent": "user.slice",
281 "BlkioWeight": 0,
282 "BlkioWeightDevice": null,
283 "BlkioDeviceReadBps": null,
284 "BlkioDeviceWriteBps": null,
285 "BlkioDeviceReadIOps": null,
286 "BlkioDeviceWriteIOps": null,
287 "CpuPeriod": 0,
288 "CpuQuota": 0,
289 "CpuRealtimePeriod": 0,
290 "CpuRealtimeRuntime": 0,
291 "CpusetCpus": "",
292 "CpusetMems": "",
293 "Devices": [],
294 "DiskQuota": 0,
295 "KernelMemory": 0,
296 "MemoryReservation": 0,
297 "MemorySwap": 0,
298 "MemorySwappiness": 0,
299 "OomKillDisable": false,
300 "PidsLimit": 2048,
301 "Ulimits": [
302 {
303 "Name": "RLIMIT_NOFILE",
304 "Soft": 524288,
305 "Hard": 524288
306 },
307 {
308 "Name": "RLIMIT_NPROC",
309 "Soft": 256018,
310 "Hard": 256018
311 }
312 ],
313 "CpuCount": 0,
314 "CpuPercent": 0,
315 "IOMaximumIOps": 0,
316 "IOMaximumBandwidth": 0,
317 "CgroupConf": null,
318 }
319 }
320 ]
321 """
322
323 import json
324 import time
325 from ansible.module_utils.basic import AnsibleModule
326
327
328 def get_containers_facts(module, executable, name):
329 """Collect containers facts for all containers or for specified in 'name'.
330
331 Arguments:
332 module {AnsibleModule} -- instance of AnsibleModule
333 executable {string} -- binary to execute when inspecting containers
334 name {list} -- list of names or None in case of all containers
335
336 Returns:
337 list of containers info, stdout, stderr
338 """
339 retry = 0
340 retry_limit = 4
341 if not name:
342 all_names = [executable, "container", "ls", "-q", "-a"]
343 rc, out, err = module.run_command(all_names)
344 # This should not fail in regular circumstances, so retry again
345 # https://github.com/containers/podman/issues/10225
346 while rc != 0 and retry <= retry_limit:
347 module.log(msg="Unable to get list of containers: %s" % err)
348 time.sleep(1)
349 retry += 1
350 rc, out, err = module.run_command(all_names)
351 if rc != 0:
352 module.fail_json(msg="Unable to get list of containers during" " %s retries" % retry_limit)
353 name = out.split()
354 if not name:
355 return [], out, err
356 command = [executable, "container", "inspect"]
357 command.extend(name)
358 rc, out, err = module.run_command(command)
359 if rc == 0:
360 json_out = json.loads(out) if out else None
361 if json_out is None:
362 return [], out, err
363 return json_out, out, err
364 if rc != 0 and "no such " in err:
365 if len(name) < 2:
366 return [], out, err
367 return cycle_over(module, executable, name)
368 module.fail_json(msg="Unable to gather info for %s: %s" % (",".join(name), err))
369
370
371 def cycle_over(module, executable, name):
372 """Inspect each container in a cycle in case some of them don't exist.
373
374 Arguments:
375 module {AnsibleModule} -- instance of AnsibleModule
376 executable {string} -- binary to execute when inspecting containers
377 name {list} -- list of containers names to inspect
378
379 Returns:
380 list of containers info, stdout as empty, stderr
381 """
382 inspection = []
383 stderrs = []
384 for container in name:
385 command = [executable, "container", "inspect", container]
386 rc, out, err = module.run_command(command)
387 if rc != 0 and "no such " not in err:
388 module.fail_json(msg="Unable to gather info for %s: %s" % (container, err))
389 if rc == 0 and out:
390 json_out = json.loads(out)
391 if json_out:
392 inspection += json_out
393 stderrs.append(err)
394 return inspection, "", "\n".join(stderrs)
395
396
397 def main():
398 module = AnsibleModule(
399 argument_spec={
400 "executable": {"type": "str", "default": "podman"},
401 "name": {"type": "list", "elements": "str"},
402 },
403 supports_check_mode=True,
404 )
405
406 name = module.params["name"]
407 executable = module.get_bin_path(module.params["executable"], required=True)
408 # pylint: disable=unused-variable
409 inspect_results, out, err = get_containers_facts(module, executable, name)
410
411 results = {"changed": False, "containers": inspect_results, "stderr": err}
412
413 module.exit_json(**results)
414
415
416 if __name__ == "__main__":
417 main()