-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
coordinator.py
251 lines (229 loc) · 9.33 KB
/
coordinator.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""Portainer coordinator."""
from __future__ import annotations
from asyncio import Lock as Asyncio_lock, wait_for as asyncio_wait_for
from datetime import timedelta
from logging import getLogger
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_API_KEY,
CONF_HOST,
CONF_NAME,
CONF_SSL,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import (
DOMAIN,
SCAN_INTERVAL,
CUSTOM_ATTRIBUTE_ARRAY,
# fature switch
CONF_FEATURE_HEALTH_CHECK,
DEFAULT_FEATURE_HEALTH_CHECK,
CONF_FEATURE_RESTART_POLICY,
DEFAULT_FEATURE_RESTART_POLICY,
)
from .apiparser import parse_api
from .api import PortainerAPI
_LOGGER = getLogger(__name__)
# ---------------------------
# PortainerControllerData
# ---------------------------
class PortainerCoordinator(DataUpdateCoordinator):
"""PortainerControllerData Class."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Initialize PortainerController."""
super().__init__(
hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=SCAN_INTERVAL)
)
self.hass = hass
self.name = config_entry.data[CONF_NAME]
self.host = config_entry.data[CONF_HOST]
# init custom features
self.features = {
CONF_FEATURE_HEALTH_CHECK: config_entry.options.get(
CONF_FEATURE_HEALTH_CHECK, DEFAULT_FEATURE_HEALTH_CHECK
),
CONF_FEATURE_RESTART_POLICY: config_entry.options.get(
CONF_FEATURE_RESTART_POLICY, DEFAULT_FEATURE_RESTART_POLICY
),
}
self.data = {
"endpoints": {},
"containers": {},
}
self.lock = Asyncio_lock()
self.api = PortainerAPI(
hass,
config_entry.data[CONF_HOST],
config_entry.data[CONF_API_KEY],
config_entry.data[CONF_SSL],
config_entry.data[CONF_VERIFY_SSL],
)
self._systemstats_errored = []
self.datasets_hass_device_id = None
# ---------------------------
# connected
# ---------------------------
def connected(self) -> bool:
"""Return connected state."""
return self.api.connected()
# ---------------------------
# _async_update_data
# ---------------------------
async def _async_update_data(self) -> None:
"""Update Portainer data."""
try:
await asyncio_wait_for(self.lock.acquire(), timeout=10)
except Exception:
return
try:
await self.hass.async_add_executor_job(self.get_endpoints)
await self.hass.async_add_executor_job(self.get_containers)
except Exception as error:
self.lock.release()
raise UpdateFailed(error) from error
self.lock.release()
async_dispatcher_send(self.hass, "update_sensors", self)
return self.data
# ---------------------------
# get_endpoints
# ---------------------------
def get_endpoints(self) -> None:
"""Get endpoints."""
self.data["endpoints"] = parse_api(
data={},
source=self.api.query("endpoints"),
key="Id",
vals=[
{"name": "Id", "default": 0},
{"name": "Name", "default": "unknown"},
{"name": "Snapshots", "default": "unknown"},
{"name": "Type", "default": 0},
{"name": "Status", "default": 0},
],
)
if not self.data["endpoints"]:
return
for uid in self.data["endpoints"]:
self.data["endpoints"][uid] = parse_api(
data=self.data["endpoints"][uid],
source=self.data["endpoints"][uid]["Snapshots"][0],
vals=[
{"name": "DockerVersion", "default": "unknown"},
{"name": "Swarm", "default": False},
{"name": "TotalCPU", "default": 0},
{"name": "TotalMemory", "default": 0},
{"name": "RunningContainerCount", "default": 0},
{"name": "StoppedContainerCount", "default": 0},
{"name": "HealthyContainerCount", "default": 0},
{"name": "UnhealthyContainerCount", "default": 0},
{"name": "VolumeCount", "default": 0},
{"name": "ImageCount", "default": 0},
{"name": "ServiceCount", "default": 0},
{"name": "StackCount", "default": 0},
],
)
del self.data["endpoints"][uid]["Snapshots"]
# ---------------------------
# get_containers
# ---------------------------
def get_containers(self) -> None:
self.data["containers"] = {}
for eid in self.data["endpoints"]:
self.data["containers"] = parse_api(
data=self.data["containers"],
source=self.api.query(
f"endpoints/{eid}/docker/containers/json", "get", {"all": True}
),
key="Id",
vals=[
{"name": "Id", "default": "unknown"},
{"name": "Names", "default": "unknown"},
{"name": "Image", "default": "unknown"},
{"name": "State", "default": "unknown"},
{"name": "Ports", "default": "unknown"},
{
"name": "Network",
"source": "HostConfig/NetworkMode",
"default": "unknown",
},
{
"name": "Compose_Stack",
"source": "Labels/com.docker.compose.project",
"default": "",
},
{
"name": "Compose_Service",
"source": "Labels/com.docker.compose.service",
"default": "",
},
{
"name": "Compose_Version",
"source": "Labels/com.docker.compose.version",
"default": "",
},
],
ensure_vals=[
{"name": "Name", "default": "unknown"},
{"name": "EndpointId", "default": eid},
{"name": CUSTOM_ATTRIBUTE_ARRAY, "default": {}},
],
)
for cid in self.data["containers"]:
self.data["containers"][cid]["Environment"] = self.data["endpoints"][
eid
]["Name"]
self.data["containers"][cid]["Name"] = self.data["containers"][cid][
"Names"
][0][1:]
# only if some custom feature is enabled
if (
self.features[CONF_FEATURE_HEALTH_CHECK]
or self.features[CONF_FEATURE_RESTART_POLICY]
):
for cid in self.data["containers"]:
self.data["containers"][cid][CUSTOM_ATTRIBUTE_ARRAY + "_Raw"] = (
parse_api(
data={},
source=self.api.query(
f"endpoints/{eid}/docker/containers/{cid}/json",
"get",
{"all": True},
),
vals=[
{
"name": "Health_Status",
"source": "State/Health/Status",
"default": "unknown",
},
{
"name": "Restart_Policy",
"source": "HostConfig/RestartPolicy/Name",
"default": "unknown",
},
],
ensure_vals=[
{"name": "Health_Status", "default": "unknown"},
{"name": "Restart_Policy", "default": "unknown"},
],
)
)
if self.features[CONF_FEATURE_HEALTH_CHECK]:
self.data["containers"][cid][CUSTOM_ATTRIBUTE_ARRAY][
"Health_Status"
] = self.data["containers"][cid][
CUSTOM_ATTRIBUTE_ARRAY + "_Raw"
][
"Health_Status"
]
if self.features[CONF_FEATURE_RESTART_POLICY]:
self.data["containers"][cid][CUSTOM_ATTRIBUTE_ARRAY][
"Restart_Policy"
] = self.data["containers"][cid][
CUSTOM_ATTRIBUTE_ARRAY + "_Raw"
][
"Restart_Policy"
]
del self.data["containers"][cid][CUSTOM_ATTRIBUTE_ARRAY + "_Raw"]