Skip to content

Commit 9b853d8

Browse files
committed
Merge branch 'develop' of github.com:nicolargo/glances into develop
2 parents f4c7ca0 + 99e6507 commit 9b853d8

File tree

6 files changed

+56
-64
lines changed

6 files changed

+56
-64
lines changed

glances/exports/glances_influxdb/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def export(self, name, columns, points):
156156
try:
157157
self.client.write_points(self._normalize(name, columns, points), time_precision="s")
158158
except Exception as e:
159-
# Log level set to debug instead of error (see: issue #1561)
160-
logger.debug(f"Cannot export {name} stats to InfluxDB ({e})")
159+
# Log level set to warning instead of error (see: issue #1561)
160+
logger.warning(f"Cannot export {name} stats to InfluxDB ({e})")
161161
else:
162162
logger.debug(f"Export {name} stats to InfluxDB")

glances/exports/glances_influxdb2/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def export(self, name, columns, points):
164164
try:
165165
self.client.write(self.bucket, self.org, self._normalize(name, columns, points), time_precision="s")
166166
except Exception as e:
167-
# Log level set to debug instead of error (see: issue #1561)
168-
logger.debug(f"Cannot export {name} stats to InfluxDB ({e})")
167+
# Log level set to warning instead of error (see: issue #1561)
168+
logger.warning(f"Cannot export {name} stats to InfluxDB ({e})")
169169
else:
170170
logger.debug(f"Export {name} stats to InfluxDB")

glances/plugins/containers/__init__.py

Lines changed: 41 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@
88

99
"""Containers plugin."""
1010

11-
import os
1211
from copy import deepcopy
12+
from typing import Any, Dict, List, Optional, Tuple
1313

14+
from glances.globals import iteritems, itervalues
1415
from glances.logger import logger
15-
from glances.plugins.containers.engines.docker import DockerContainersExtension, import_docker_error_tag
16-
from glances.plugins.containers.engines.podman import PodmanContainersExtension, import_podman_error_tag
16+
from glances.plugins.containers.engines import ContainersExtension
17+
from glances.plugins.containers.engines.docker import DockerExtension, import_docker_error_tag
18+
from glances.plugins.containers.engines.podman import PodmanExtension, import_podman_error_tag
1719
from glances.plugins.plugin.model import GlancesPluginModel
1820
from glances.processes import glances_processes
1921
from glances.processes import sort_stats as sort_stats_processes
@@ -139,14 +141,15 @@ def __init__(self, args=None, config=None):
139141
# We want to display the stat in the curse interface
140142
self.display_curse = True
141143

144+
self.watchers: Dict[str, ContainersExtension] = {}
145+
142146
# Init the Docker API
143-
self.docker_extension = DockerContainersExtension() if not import_docker_error_tag else None
147+
if not import_docker_error_tag:
148+
self.watchers['docker'] = DockerExtension()
144149

145150
# Init the Podman API
146-
if import_podman_error_tag:
147-
self.podman_extension = None
148-
else:
149-
self.podman_extension = PodmanContainersExtension(podman_sock=self._podman_sock())
151+
if not import_podman_error_tag:
152+
self.watchers['podman'] = PodmanExtension(podman_sock=self._podman_sock())
150153

151154
# Sort key
152155
self.sort_key = None
@@ -155,7 +158,7 @@ def __init__(self, args=None, config=None):
155158
self.update()
156159
self.refresh_timer.set(0)
157160

158-
def _podman_sock(self):
161+
def _podman_sock(self) -> str:
159162
"""Return the podman sock.
160163
Could be desfined in the [docker] section thanks to the podman_sock option.
161164
Default value: unix:///run/user/1000/podman/podman.sock
@@ -165,20 +168,19 @@ def _podman_sock(self):
165168
return "unix:///run/user/1000/podman/podman.sock"
166169
return conf_podman_sock[0]
167170

168-
def exit(self):
171+
def exit(self) -> None:
169172
"""Overwrite the exit method to close threads."""
170-
if self.docker_extension:
171-
self.docker_extension.stop()
172-
if self.podman_extension:
173-
self.podman_extension.stop()
173+
for watcher in itervalues(self.watchers):
174+
watcher.stop()
175+
174176
# Call the father class
175177
super().exit()
176178

177-
def get_key(self):
179+
def get_key(self) -> str:
178180
"""Return the key of the list."""
179181
return 'name'
180182

181-
def get_export(self):
183+
def get_export(self) -> List[Dict]:
182184
"""Overwrite the default export method.
183185
184186
- Only exports containers
@@ -197,7 +199,7 @@ def get_export(self):
197199

198200
return ret
199201

200-
def _all_tag(self):
202+
def _all_tag(self) -> bool:
201203
"""Return the all tag of the Glances/Docker configuration file.
202204
203205
# By default, Glances only display running containers
@@ -211,52 +213,35 @@ def _all_tag(self):
211213

212214
@GlancesPluginModel._check_decorator
213215
@GlancesPluginModel._log_result_decorator
214-
def update(self):
216+
def update(self) -> List[Dict]:
215217
"""Update Docker and podman stats using the input method."""
216218
# Connection should be ok
217-
if self.docker_extension is None and self.podman_extension is None:
219+
if not self.watchers:
220+
return self.get_init_value()
221+
222+
if self.input_method != 'local':
218223
return self.get_init_value()
219224

220-
if self.input_method == 'local':
221-
# Update stats
222-
stats_docker = self.update_docker() if self.docker_extension else {}
223-
stats_podman = self.update_podman() if self.podman_extension else {}
224-
stats = stats_docker.get('containers', []) + stats_podman.get('containers', [])
225-
elif self.input_method == 'snmp':
226-
# Update stats using SNMP
227-
# Not available
228-
pass
225+
# Update stats
226+
stats = []
227+
for engine, watcher in iteritems(self.watchers):
228+
version, containers = watcher.update(all_tag=self._all_tag())
229+
for container in containers:
230+
container["engine"] = 'docker'
231+
stats.extend(containers)
229232

230233
# Sort and update the stats
231234
# @TODO: Have a look because sort did not work for the moment (need memory stats ?)
232235
self.sort_key, self.stats = sort_docker_stats(stats)
233-
234236
return self.stats
235237

236-
def update_docker(self):
237-
"""Update Docker stats using the input method."""
238-
version, containers = self.docker_extension.update(all_tag=self._all_tag())
239-
for container in containers:
240-
container["engine"] = 'docker'
241-
return {"version": version, "containers": containers}
242-
243-
def update_podman(self):
244-
"""Update Podman stats."""
245-
version, containers = self.podman_extension.update(all_tag=self._all_tag())
246-
for container in containers:
247-
container["engine"] = 'podman'
248-
return {"version": version, "containers": containers}
249-
250-
def get_user_ticks(self):
251-
"""Return the user ticks by reading the environment variable."""
252-
return os.sysconf(os.sysconf_names['SC_CLK_TCK'])
253-
254-
def memory_usage_no_cache(self, mem):
238+
@staticmethod
239+
def memory_usage_no_cache(mem: Dict[str, float]) -> float:
255240
"""Return the 'real' memory usage by removing inactive_file to usage"""
256241
# Ref: https://github.com/docker/docker-py/issues/3210
257242
return mem['usage'] - (mem['inactive_file'] if 'inactive_file' in mem else 0)
258243

259-
def update_views(self):
244+
def update_views(self) -> bool:
260245
"""Update stats views."""
261246
# Call the father's method
262247
super().update_views()
@@ -305,7 +290,7 @@ def update_views(self):
305290

306291
return True
307292

308-
def msg_curse(self, args=None, max_width=None):
293+
def msg_curse(self, args=None, max_width: Optional[int] = None) -> List[str]:
309294
"""Return the dict to display in the curse interface."""
310295
# Init the return message
311296
ret = []
@@ -369,7 +354,9 @@ def msg_curse(self, args=None, max_width=None):
369354
if self.views['show_pod_name']:
370355
ret.append(self.curse_add_line(' {:{width}}'.format(container.get("pod_id", "-"), width=12)))
371356
# Name
372-
ret.append(self.curse_add_line(self._msg_name(container=container, max_width=name_max_width)))
357+
ret.append(
358+
self.curse_add_line(' {:{width}}'.format(container['name'][:name_max_width], width=name_max_width))
359+
)
373360
# Status
374361
status = self.container_alert(container['status'])
375362
msg = '{:>10}'.format(container['status'][0:10])
@@ -441,12 +428,8 @@ def msg_curse(self, args=None, max_width=None):
441428

442429
return ret
443430

444-
def _msg_name(self, container, max_width):
445-
"""Build the container name."""
446-
name = container['name'][:max_width]
447-
return ' {:{width}}'.format(name, width=max_width)
448-
449-
def container_alert(self, status):
431+
@staticmethod
432+
def container_alert(status: str) -> str:
450433
"""Analyse the container status."""
451434
if status == 'running':
452435
return 'OK'
@@ -457,7 +440,7 @@ def container_alert(self, status):
457440
return 'CAREFUL'
458441

459442

460-
def sort_docker_stats(stats):
443+
def sort_docker_stats(stats: List[Dict[str, Any]]) -> Tuple[str, List[Dict[str, Any]]]:
461444
# Sort Docker stats using the same function than processes
462445
sort_by = glances_processes.sort_key
463446
sort_by_secondary = 'memory_usage'
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from typing import Any, Dict, Protocol, Tuple
2+
3+
4+
class ContainersExtension(Protocol):
5+
def stop(self) -> None:
6+
raise NotImplementedError
7+
8+
def update(self, all_tag) -> Tuple[Dict, list[Dict[str, Any]]]:
9+
raise NotImplementedError

glances/plugins/containers/engines/docker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def _get_io_stats(self) -> Optional[Dict[str, float]]:
207207
return stats
208208

209209

210-
class DockerContainersExtension:
210+
class DockerExtension:
211211
"""Glances' Containers Plugin's Docker Extension unit"""
212212

213213
CONTAINER_ACTIVE_STATUS = ['running', 'paused']

glances/plugins/containers/engines/podman.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ def _get_io_stats(self, stats) -> Optional[Dict]:
243243
return {"ior": ior, "iow": iow, "time_since_update": 1}
244244

245245

246-
class PodmanContainersExtension:
246+
class PodmanExtension:
247247
"""Glances' Containers Plugin's Docker Extension unit"""
248248

249249
CONTAINER_ACTIVE_STATUS = ['running', 'paused']

0 commit comments

Comments
 (0)