-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanager.py
276 lines (226 loc) · 9.46 KB
/
manager.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""
Deployment API Manager
"""
import json
from datetime import timedelta
from enum import Enum
from nio.util.versioning.dependency import DependsOn
from nio import discoverable
from nio.modules.settings import Settings
from nio.modules.persistence import Persistence
from nio.modules.scheduler.job import Job
from niocore.core.component import CoreComponent
from .handler import DeploymentHandler
from .proxy import DeploymentProxy
@DependsOn('niocore.components.rest')
@discoverable
class DeploymentManager(CoreComponent):
""" Handle configuration updates
"""
class Status(Enum):
started = 1
accepted = 2
in_progress = 3
success = 4
failure = 5
_name = "DeploymentManager"
def __init__(self):
super().__init__()
self._rest_manager = None
self._config_handler = None
self._api_proxy = None
self._configuration_manager = None
self._config_api_url_prefix = None
self._config_id = None
self._config_version_id = None
self._poll_job = None
self._poll = None
self._poll_interval = None
self._poll_on_start = None
self._start_stop_services = None
self._delete_missing = None
def configure(self, context):
""" Configures component
Establish dependency to RESTManager
Fetches settings
Args:
context (CoreContext): component initialization context
"""
super().configure(context)
# Register dependency to rest manager
self._rest_manager = self.get_dependency('RESTManager')
self._configuration_manager = \
self.get_dependency('ConfigurationManager')
self._api_key_manager = self.get_dependency('APIKeyManager')
# fetch component settings
self._config_api_url_prefix = \
Settings.get("configuration", "config_api_url_prefix",
fallback="https://api.n.io/v1")
self._config_id = Persistence().load(
"configuration_id",
default=Settings.get("configuration", "config_id"))
self._config_version_id = Persistence().load(
"configuration_version_id",
default=Settings.get("configuration", "config_version_id"))
self._start_stop_services = Settings.getboolean(
"configuration", "start_stop_services", fallback=True)
self._delete_missing = Settings.getboolean(
"configuration", "delete_missing", fallback=True)
self._poll_interval = Settings.getint(
"configuration", "config_poll_interval", fallback=0)
self._poll_on_start = Settings.getboolean(
"configuration", "config_poll_on_start", fallback=False)
def start(self):
""" Starts component
Instantiates DeploymentHandler and DeploymentProxy
Begins polling job if it is set
"""
super().start()
self._api_proxy = DeploymentProxy(self._config_api_url_prefix, self)
self._config_handler = DeploymentHandler(self)
self._rest_manager.add_web_handler(self._config_handler)
if self._poll_interval:
self._poll_job = Job(self._run_config_update,
timedelta(seconds=self._poll_interval),
True)
if self._poll_on_start:
self._run_config_update()
def stop(self):
""" Stops component
"""
self._rest_manager.remove_web_handler(self._config_handler)
if self._poll_job:
self._poll_job.cancel()
self._poll_job = None
super().stop()
@property
def api_key(self):
return self._api_key_manager.api_key
@property
def instance_id(self):
return self._api_key_manager.instance_id
def _run_config_update(self):
"""Callback function to run update at each polling interval """
self.logger.debug("Checking for latest configuration")
# Poll the product api for config ids this instance
# should be running
ids = self._api_proxy.get_instance_config_ids()
if ids is None:
# It didn't report any IDs to update to, so ignore
return
self.logger.debug("Desired configuration: {}".format(ids))
config_id = ids.get("instance_configuration_id")
config_version_id = ids.get("instance_configuration_version_id")
if config_id == self.config_id and \
config_version_id == self.config_version_id:
self.logger.debug(
"No change detected from current version, skipping")
return
self.logger.info(
"New configuration detected...updating to config ID {} "
"version {}".format(config_id, config_version_id))
deployment_id = ids.get("deployment_id")
result = self.update_configuration(
config_id, config_version_id, deployment_id)
self.logger.info("Configuration was updated: {}".format(result))
def update_configuration(
self, config_id, config_version_id, deployment_id):
""" Update this instance to a given config/version ID.
Args:
config_id: The ID of the instance configuration to use
config_version_id: The version ID of the instance config
deployment_id: The deployment ID to set the status for
Returns:
result (dict): The result of the instance update call
"""
# grab new configuration
configuration = self._api_proxy.get_configuration(
config_id, config_version_id)
if configuration is None or "configuration_data" not in configuration:
msg = "configuration_data entry missing in nio API return"
self.logger.error(msg)
raise RuntimeError(msg)
configuration_data = json.loads(configuration["configuration_data"])
# notify configuration acceptance
self._api_proxy.set_reported_configuration(
config_id,
config_version_id,
deployment_id,
self.Status.accepted.name,
"Services and Blocks configuration was accepted, "
"proceeding with update")
# perform update
result = self._configuration_manager.update(
configuration_data,
self._start_stop_services,
self._delete_missing)
# instance is now running this configuration so persist this fact
self.config_id = config_id
self.config_version_id = config_version_id
error_messages = self._get_potential_errors_messages(result)
if error_messages:
# notify failure
self._api_proxy.set_reported_configuration(
config_id,
config_version_id,
deployment_id,
self.Status.failure.name,
"Failed to update, these errors were encountered: {}".format(
error_messages))
else:
# report success and new instance config ids
self._api_proxy.set_reported_configuration(
config_id,
config_version_id,
deployment_id,
self.Status.success.name,
"Successfully updated services and blocks")
self.logger.info("Configuration was updated, {}".format(result))
return result
def _get_potential_errors_messages(self, result):
"""Return any error messages contained in a result"""
messages = []
for key in result.keys():
errors = result.get(key, {}).get("error", [])
if errors:
message = "Failed to install {}".format(key)
for error in errors:
if isinstance(error, dict):
message += ", {}".format(json.dumps(error))
# providing API should send errors as dicts but just in
# case it does not, at least attempt to convert to str
else:
message += ", " + str(error)
messages.append(message)
# do not let errors go unnoticed
self.logger.error("{} error: {}".format(key, errors))
str_messages = ",".join(messages)
if messages:
self.logger.error(
"{} errors were encountered during update: {}".format(
len(messages), str_messages))
return str_messages
@property
def config_id(self):
return self._config_id
@config_id.setter
def config_id(self, config_id):
if self._config_id != config_id:
self.logger.debug("Configuration ID set to: {}".format(config_id))
self._config_id = config_id
# persist value so that it can be read eventually
# when component starts again
Persistence().save(self.config_id, "configuration_id")
@property
def config_version_id(self):
return self._config_version_id
@config_version_id.setter
def config_version_id(self, config_version_id):
if self._config_version_id != config_version_id:
self.logger.debug("Configuration Version ID set to: {}".
format(config_version_id))
self._config_version_id = config_version_id
# persist value so that it can be read eventually
# when component starts again
Persistence().save(
self.config_version_id, "configuration_version_id")