Projet

Général

Profil

Paste
Télécharger au format
Statistiques
| Branche: | Révision:

root / plugins / docker / docker_ @ 24825188

Historique | Voir | Annoter | Télécharger (18,2 ko)

1
#!/usr/bin/env python3
2
"""
3
=head1 NAME
4

    
5
docker_ - Docker wildcard-plugin to monitor a L<Docker|https://www.docker.com> host.
6

    
7
This wildcard plugin provides at the moment only the suffixes C<containers>, C<images>, C<status>,
8
C<volumes>, C<cpu>, C<memory> and C<network>.
9

    
10
=head1 INSTALLATION
11

    
12
- Copy this plugin in your munin plugins directory
13
- Install Python3 "docker" package
14

    
15
=over 2
16

    
17
    ln -s /usr/share/munin/plugins/docker_ /etc/munin/plugins/docker_containers
18
    ln -s /usr/share/munin/plugins/docker_ /etc/munin/plugins/docker_cpu
19
    ln -s /usr/share/munin/plugins/docker_ /etc/munin/plugins/docker_images
20
    ln -s /usr/share/munin/plugins/docker_ /etc/munin/plugins/docker_memory
21
    ln -s /usr/share/munin/plugins/docker_ /etc/munin/plugins/docker_network
22
    ln -s /usr/share/munin/plugins/docker_ /etc/munin/plugins/docker_status
23
    ln -s /usr/share/munin/plugins/docker_ /etc/munin/plugins/docker_volumes
24

    
25
=back
26

    
27
After the installation you need to restart your munin-node:
28

    
29
=over 2
30

    
31
    systemctl restart munin-node
32

    
33
=back
34

    
35
=head1 CONFIGURATION
36

    
37
This plugin need to run as root, you need to create a file named docker placed in the
38
directory /etc/munin/plugin-conf.d/ with the following config (you can also use
39
Docker environment variables here as described in
40
https://docs.docker.com/compose/reference/envvars/):
41

    
42
You can use the EXCLUDE_CONTAINER_NAME environment variable to specify a regular expression
43
which if matched will exclude the matching containers from the memory and cpu graphs.
44

    
45
For example
46

    
47
 env.EXCLUDE_CONTAINER_NAME runner
48

    
49
Would exclude all containers with the word "runner" in the name.
50

    
51

    
52
=over 2
53

    
54
    [docker_*]
55
    user root
56
    env.DOCKER_HOST unix://var/run/docker.sock
57
    env.EXCLUDE_CONTAINER_NAME regexp
58

    
59
=back
60

    
61
=head1 AUTHORS
62

    
63
This section has been reverse-engineered from git logs
64

    
65
* Codimp <contact@lithio.fr>: original rewrite
66

    
67
* Rowan Wookey <admin@rwky.net>: performance improvement
68

    
69
* Olivier Mehani <shtrom@ssji.net>: Network support, ClientWrapper, gerenal cleanup
70

    
71
=head1 MAGIC MARKERS
72

    
73
 #%# family=auto
74
 #%# capabilities=autoconf suggest
75

    
76
=cut
77
"""
78

    
79
import os
80
import sys
81
import re
82
try:
83
    from functools import cached_property
84
except ImportError:
85
    # If cached_property is not available,
86
    # just use the property decorator, without caching
87
    # This is for backward compatibility with Python<3.8
88
    cached_property = property
89
from multiprocessing import Process, Queue
90

    
91

    
92
def sorted_by_creation_date(func):
93
    def sorted_func(*args, **kwargs):
94
        return sorted(
95
            func(*args, **kwargs),
96
            key=(
97
                lambda x: x.attrs['CreatedAt']
98
                if 'CreatedAt' in x.attrs
99
                else x.attrs['Created']
100
            )
101
        )
102
    return sorted_func
103

    
104

    
105
class ClientWrapper:
106
    """
107
    A small wrapper for the docker client, to centralise some parsing logic,
108
    and support caching.
109

    
110
    In addition, when the exclude_re parameter is not None,
111
    any container which name is matched by the RE will not be excluded from reports.
112
    """
113
    client = None
114
    exclude = None
115

    
116
    def __init__(self, client, exclude_re=None):
117
        self.client = client
118
        if exclude_re:
119
            self.exclude = re.compile(exclude_re)
120

    
121
    @property
122
    def api(self):
123
        return self.client.api
124

    
125
    @cached_property
126
    @sorted_by_creation_date
127
    def containers(self):
128
        return self.client.containers.list()
129

    
130
    @cached_property
131
    @sorted_by_creation_date
132
    def all_containers(self):
133
        return [c for c in self.client.containers.list(all=True)
134
                if not self.exclude
135
                or not self.exclude.search(c.name)]
136

    
137
    @cached_property
138
    @sorted_by_creation_date
139
    def intermediate_images(self):
140
        return list(
141
            set(self.all_images)
142
            .difference(
143
                set(self.images)
144
                .difference(
145
                    set(self.dangling_images)
146
                )
147
            )
148
        )
149

    
150
    @cached_property
151
    @sorted_by_creation_date
152
    def all_images(self):
153
        return self.client.images.list(all=True)
154

    
155
    @cached_property
156
    @sorted_by_creation_date
157
    def images(self):
158
        images = self.client.images.list()
159
        return list(
160
            set(images)
161
            .difference(
162
                set(self.dangling_images))
163
        )
164

    
165
    @cached_property
166
    @sorted_by_creation_date
167
    def dangling_images(self):
168
        return self.client.images.list(filters={'dangling': True})
169

    
170
    @cached_property
171
    @sorted_by_creation_date
172
    def volumes(self):
173
        return self.client.volumes.list()
174

    
175

    
176
def container_summary(container, *args):
177
    summary = container.name
178
    attributes = container_attributes(container, *args)
179
    if attributes:
180
        summary += f' ({attributes})'
181
    return summary
182

    
183

    
184
def container_attributes(container, *args):
185
    attributes = container.image.tags
186
    attributes.append(container.attrs['Created'])
187
    return ', '.join(attributes + list(args))
188

    
189

    
190
def print_containers_status(client):
191
    running = []
192
    unhealthy = []
193
    paused = []
194
    created = []
195
    restarting = []
196
    removing = []
197
    exited = []
198
    dead = []
199
    for container in client.all_containers:
200
        if container.status == 'running':
201
            state = client.api.inspect_container(container.name)['State']
202
            if state.get('Health', {}).get('Status') == 'unhealthy':
203
                unhealthy.append(container)
204
            else:
205
                running.append(container)
206
        elif container.status == 'paused':
207
            paused.append(container)
208
        elif container.status == 'created':
209
            created.append(container)
210
        elif container.status == 'restarting':
211
            restarting.append(container)
212
        elif container.status == 'removing':
213
            removing.append(container)
214
        elif container.status == 'exited':
215
            exited.append(container)
216
        elif container.status == 'dead':
217
            dead.append(container)
218
    print('running.value', len(running))
219
    print('running.extinfo', ', '.join(container_summary(c) for c in running))
220
    print('unhealthy.value', len(unhealthy))
221
    print('unhealthy.extinfo', ', '.join(container_summary(c) for c in unhealthy))
222
    print('paused.value', len(paused))
223
    print('paused.extinfo', ', '.join(container_summary(c) for c in paused))
224
    print('created.value', len(created))
225
    print('created.extinfo', ', '.join(container_summary(c) for c in created))
226
    print('restarting.value', len(restarting))
227
    print('restarting.extinfo', ', '.join(container_summary(c) for c in restarting))
228
    print('removing.value', len(removing))
229
    print('removing.extinfo', ', '.join(container_summary(c) for c in removing))
230
    print('exited.value', len(exited))
231
    print('exited.extinfo', ', '.join(container_summary(c) for c in exited))
232
    print('dead.value', len(dead))
233
    print('dead.extinfo', ', '.join(container_summary(c) for c in dead))
234

    
235

    
236
def image_summary(image):
237
    attributes = image.tags
238
    attributes.append(image.attrs['Created'])
239
    attributes.append(f"{round(image.attrs['Size']/1024**2, 2)} MiB")
240
    return f"{image.short_id} ({', '.join(attributes)})"
241

    
242

    
243
def print_images_count(client):
244
    images = client.images
245
    intermediate = client.intermediate_images
246
    dangling = client.dangling_images
247

    
248
    print('intermediate_quantity.value', len(intermediate))
249
    print('intermediate_quantity.extinfo', ', '.join(image_summary(i) for i in intermediate))
250
    print('images_quantity.value', len(images))
251
    print('images_quantity.extinfo', ', '.join(image_summary(i) for i in images))
252
    print('dangling_quantity.value', len(dangling))
253
    print('dangling_quantity.extinfo', ', '.join(image_summary(i) for i in dangling))
254

    
255

    
256
def get_container_stats(container, q):
257
    q.put(container.stats(stream=False))
258

    
259

    
260
def parallel_container_stats(client):
261
    proc_list = []
262
    stats = {}
263
    for container in client.containers:
264
        q = Queue()
265
        p = Process(target=get_container_stats, args=(container, q))
266
        proc_list.append({'proc': p, 'queue': q, 'container': container})
267
        p.start()
268
    for proc in proc_list:
269
        proc['proc'].join()
270
        stats[proc['container']] = proc['queue'].get()
271
    return stats.items()
272

    
273

    
274
def print_containers_cpu(client):
275
    for container, stats in parallel_container_stats(client):
276
        cpu_percent = 0.0
277
        cpu_delta = (float(stats["cpu_stats"]["cpu_usage"]["total_usage"])
278
                     - float(stats["precpu_stats"]["cpu_usage"]["total_usage"]))
279
        system_delta = (float(stats["cpu_stats"]["system_cpu_usage"])
280
                        - float(stats["precpu_stats"]["system_cpu_usage"]))
281
        if system_delta > 0.0:
282
            cpu_percent = cpu_delta / system_delta * 100.0 * os.cpu_count()
283
        print(container.name + '.value', cpu_percent)
284
        print(container.name + '.extinfo', container_attributes(container))
285

    
286

    
287
def print_containers_memory(client):
288
    for container, stats in parallel_container_stats(client):
289
        if 'total_rss' in stats['memory_stats']['stats']:  # cgroupv1 only?
290
            memory_usage = stats['memory_stats']['stats']['total_rss']
291
            extinfo = 'Resident Set Size'
292
        else:
293
            memory_usage = stats['memory_stats']['usage']
294
            extinfo = 'Total memory usage'
295
        print(container.name + '.value', memory_usage)
296
        print(container.name + '.extinfo', container_attributes(container, extinfo))
297

    
298

    
299
def print_containers_network(client):
300
    for container, stats in parallel_container_stats(client):
301
        tx_bytes = 0
302
        rx_bytes = 0
303
        for data in stats['networks'].values():
304
            tx_bytes += data['tx_bytes']
305
            rx_bytes += data['rx_bytes']
306
        print(container.name + '_up.value', tx_bytes)
307
        print(container.name + '_down.value', rx_bytes)
308
        print(container.name + '_up.extinfo', container_attributes(container))
309

    
310

    
311
def volume_summary(volume):
312
    summary = f"{volume.short_id}"
313
    if volume.attrs['Labels']:
314
        summary += f" ({', '.join(volume.attrs['Labels'])})"
315
    return summary
316

    
317

    
318
def main():
319
    try:
320
        mode = sys.argv[1]
321
    except IndexError:
322
        mode = ""
323
    wildcard = sys.argv[0].split("docker_")[1].split("_")[0]
324

    
325
    try:
326
        import docker
327
        client = docker.from_env()
328
        if mode == "autoconf":
329
            client.ping()
330
            print('yes')
331
            sys.exit(0)
332
    except Exception as e:
333
        print(f'no ({e})')
334
        if mode == "autoconf":
335
            sys.exit(0)
336
        sys.exit(1)
337

    
338
    if mode == "suggest":
339
        print("cpu")
340
        print("images")
341
        print("memory")
342
        print("network")
343
        print("status")
344
        print("volumes")
345
        sys.exit(0)
346

    
347
    client = ClientWrapper(client,
348
                           exclude_re=os.getenv('EXCLUDE_CONTAINER_NAME'))
349

    
350
    if wildcard == "status":
351
        if mode == "config":
352
            print("graph_title Docker status")
353
            print("graph_vlabel containers")
354
            print("graph_category virtualization")
355
            print("graph_total All containers")
356
            print("running.label RUNNING")
357
            print("running.draw AREASTACK")
358
            print("running.info Running containers can be manipulated with "
359
                  "`docker container [attach|kill|logs|pause|restart|stop] <NAME>` or "
360
                  "commands run in them with `docker container exec "
361
                  "[--detach|--interactive,--privileged,--tty] <NAME> <COMMAND>`"
362
                  )
363
            print("unhealthy.label UNHEALTHY")
364
            print("unhealthy.draw AREASTACK")
365
            print("unhealthy.warning 1")
366
            print("unhealthy.info Unhealthy containers can be restarted with "
367
                  "`docker container restart <NAME>`")
368
            print("paused.label PAUSED")
369
            print("paused.draw AREASTACK")
370
            print("paused.info Paused containers can be resumed with "
371
                  "`docker container unpause <NAME>`")
372
            print("created.label CREATED")
373
            print("created.draw AREASTACK")
374
            print("created.info New containers can be created with "
375
                  "`docker container create --name <NAME> <IMAGE_ID >` or "
376
                  "`docker container run --name <NAME> <IMAGE_ID> <COMMAND>`")
377
            print("restarting.label RESTARTING")
378
            print("restarting.draw AREASTACK")
379
            print("restarting.info Containers can be restarted with "
380
                  "`docker container restart <NAME>`")
381
            print("removing.label REMOVING")
382
            print("removing.draw AREASTACK")
383
            print("removing.info Containers can be removed with "
384
                  "`docker container rm <NAME>`")
385
            print("exited.label EXITED")
386
            print("exited.draw AREASTACK")
387
            print("exited.info Exited containers can be started with "
388
                  "`docker container start [--attach] <NAME>`")
389
            print("dead.label DEAD")
390
            print("dead.draw AREASTACK")
391
            print("dead.warning 1")
392
            print("dead.info Dead containers can be started with "
393
                  "`docker container start <NAME>`")
394
        else:
395
            print_containers_status(client)
396
    elif wildcard == "containers":
397
        if mode == "config":
398
            print("graph_title Docker containers")
399
            print("graph_vlabel containers")
400
            print("graph_category virtualization")
401
            print("containers_quantity.label Containers")
402
        else:
403
            print('containers_quantity.value', len(client.containers))
404
    elif wildcard == "images":
405
        if mode == "config":
406
            print("graph_title Docker images")
407
            print("graph_vlabel images")
408
            print("graph_category virtualization")
409
            print("graph_total All images")
410
            print("intermediate_quantity.label Intermediate images")
411
            print("intermediate_quantity.draw AREASTACK")
412
            print("intermediate_quantity.info All unused images can be deleted with "
413
                  "`docker image prune --all`")
414
            print("images_quantity.label Images")
415
            print("images_quantity.draw AREASTACK")
416
            print("images_quantity.info Images can be used in containers with "
417
                  "`docker container create --name <NAME> <IMAGE_ID >` or "
418
                  "`docker container run --name <NAME> <IMAGE_ID> <COMMAND>`")
419
            print("dangling_quantity.label Dangling images")
420
            print("dangling_quantity.draw AREASTACK")
421
            print("dangling_quantity.info Dangling images can be deleted with "
422
                  "`docker image prune`"
423
                  "or tagged with `docker image tag <IMAGE_ID> <NAME>`")
424
            print("dangling_quantity.warning 10")
425
        else:
426
            print_images_count(client)
427
    elif wildcard == "volumes":
428
        if mode == "config":
429
            print("graph_title Docker volumes")
430
            print("graph_vlabel volumes")
431
            print("graph_category virtualization")
432
            print("volumes_quantity.label Volumes")
433
            print("volumes_quantity.draw AREASTACK")
434
            print("volumes_quantity.info Unused volumes can be deleted with "
435
                  "`docker volume prune`")
436
        else:
437
            print('volumes_quantity.value', len(client.volumes))
438
            print('volumes_quantity.extinfo', ', '.join(volume_summary(v) for v in client.volumes))
439
    elif wildcard == "cpu":
440
        if mode == "config":
441
            graphlimit = str(os.cpu_count() * 100)
442
            print("graph_title Docker containers CPU usage")
443
            print("graph_args --base 1000 -r --lower-limit 0 --upper-limit " + graphlimit)
444
            print("graph_scale no")
445
            print("graph_period second")
446
            print("graph_vlabel CPU usage (%)")
447
            print("graph_category virtualization")
448
            print("graph_info This graph shows docker container CPU usage.")
449
            print("graph_total Total CPU usage")
450
            for container in client.all_containers:
451
                print("{}.label {}".format(container.name, container.name))
452
                print("{}.draw AREASTACK".format(container.name))
453
                print("{}.info {}".format(container.name, container_attributes(container)))
454
        else:
455
            print_containers_cpu(client)
456
    elif wildcard == "memory":
457
        if mode == "config":
458
            print("graph_title Docker containers memory usage")
459
            print("graph_args --base 1024 -l 0")
460
            print("graph_vlabel Bytes")
461
            print("graph_category virtualization")
462
            print("graph_info This graph shows docker container memory usage.")
463
            print("graph_total Total memory usage")
464
            for container in client.all_containers:
465
                print("{}.label {}".format(container.name, container.name))
466
                print("{}.draw AREASTACK".format(container.name))
467
                print("{}.info {}".format(container.name, container_attributes(container)))
468
        else:
469
            print_containers_memory(client)
470
    elif wildcard == "network":
471
        if mode == "config":
472
            print("graph_title Docker containers network usage")
473
            print("graph_args --base 1024 -l 0")
474
            print("graph_vlabel bits in (-) / out (+) per ${graph_period}")
475
            print("graph_category virtualization")
476
            print("graph_info This graph shows docker container network usage.")
477
            print("graph_total Total network usage")
478
            for container in client.all_containers:
479
                print("{}_down.label {}_received".format(container.name, container.name))
480
                print("{}_down.type DERIVE".format(container.name))
481
                print("{}_down.min 0".format(container.name))
482
                print("{}_down.graph no".format(container.name))
483
                print("{}_down.cdef {}_down,8,*".format(container.name, container.name))
484
                print("{}_up.label {}".format(container.name, container.name))
485
                print("{}_up.draw LINESTACK1".format(container.name))
486
                print("{}_up.type DERIVE".format(container.name))
487
                print("{}_up.min 0".format(container.name))
488
                print("{}_up.negative {}_down".format(container.name, container.name))
489
                print("{}_up.cdef {}_up,8,*".format(container.name, container.name))
490
                print("{}_up.info {}".format(container.name, container_attributes(container)))
491
        else:
492
            print_containers_network(client)
493

    
494

    
495
if __name__ == '__main__':
496
    main()