blob: 9f9520f8f853b165d2a5db085a58c4bfcad63e7c [file] [log] [blame]
David Garcia4fee80e2020-05-13 12:18:38 +02001# Copyright 2020 Canonical Ltd.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import asyncio
16import time
17from juju.client import client
David Garcia4fee80e2020-05-13 12:18:38 +020018from n2vc.exceptions import EntityInvalidException
19from n2vc.n2vc_conn import N2VCConnector
20from juju.model import ModelEntity, Model
21from juju.client.overrides import Delta
David Garciac38a6962020-09-16 13:31:33 +020022from juju.status import derive_status
23from juju.application import Application
David Garcia2f66c4d2020-06-19 11:40:18 +020024from websockets.exceptions import ConnectionClosed
David Garcia4fee80e2020-05-13 12:18:38 +020025import logging
26
27logger = logging.getLogger("__main__")
28
29
David Garciac38a6962020-09-16 13:31:33 +020030def status(application: Application) -> str:
31 unit_status = []
32 for unit in application.units:
33 unit_status.append(unit.workload_status)
34 return derive_status(unit_status)
35
36
37def entity_ready(entity: ModelEntity) -> bool:
David Garciac3441172021-03-10 11:50:38 +010038 """
39 Check if the entity is ready
40
41 :param: entity: Model entity. It can be a machine, action, or application.
42
43 :returns: boolean saying if the entity is ready or not
44 """
David Garciac38a6962020-09-16 13:31:33 +020045 entity_type = entity.entity_type
46 if entity_type == "machine":
47 return entity.agent_status in ["started"]
48 elif entity_type == "action":
49 return entity.status in ["completed", "failed", "cancelled"]
50 elif entity_type == "application":
51 # Workaround for bug: https://github.com/juju/python-libjuju/issues/441
David Garciac3441172021-03-10 11:50:38 +010052 return entity.status in ["active", "blocked"]
David Garciac38a6962020-09-16 13:31:33 +020053 else:
54 raise EntityInvalidException("Unknown entity type: {}".format(entity_type))
55
56
David Garciac3441172021-03-10 11:50:38 +010057def application_ready(application: Application) -> bool:
58 """
59 Check if an application has a leader
60
61 :param: application: Application entity.
62
63 :returns: boolean saying if the application has a unit that is a leader.
64 """
65 ready_status_list = ["active", "blocked"]
66 application_ready = application.status in ready_status_list
67 units_ready = all(
68 unit.workload_status in ready_status_list for unit in application.units
69 )
70 return application_ready and units_ready
71
72
David Garcia4fee80e2020-05-13 12:18:38 +020073class JujuModelWatcher:
74 @staticmethod
garciadeblas82b591c2021-03-24 09:22:13 +010075 async def wait_for_model(model: Model, timeout: float = 3600):
David Garcia667696e2020-09-22 14:52:32 +020076 """
77 Wait for all entities in model to reach its final state.
78
79 :param: model: Model to observe
80 :param: timeout: Timeout for the model applications to be active
81
82 :raises: asyncio.TimeoutError when timeout reaches
83 """
84
85 if timeout is None:
86 timeout = 3600.0
87
88 # Coroutine to wait until the entity reaches the final state
David Garciac3441172021-03-10 11:50:38 +010089 async def wait_until_model_ready():
90 wait_for_entity = asyncio.ensure_future(
91 asyncio.wait_for(
92 model.block_until(
93 lambda: all(
94 application_ready(application)
95 for application in model.applications.values()
96 ),
97 ),
98 timeout=timeout,
99 )
David Garcia667696e2020-09-22 14:52:32 +0200100 )
David Garcia667696e2020-09-22 14:52:32 +0200101
David Garciac3441172021-03-10 11:50:38 +0100102 tasks = [wait_for_entity]
103 try:
104 await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
105 finally:
106 # Cancel tasks
107 for task in tasks:
108 task.cancel()
109
110 await wait_until_model_ready()
111 # Check model is still ready after 10 seconds
112
113 await asyncio.sleep(10)
114 await wait_until_model_ready()
David Garcia667696e2020-09-22 14:52:32 +0200115
116 @staticmethod
David Garcia4fee80e2020-05-13 12:18:38 +0200117 async def wait_for(
David Garcia667696e2020-09-22 14:52:32 +0200118 model: Model,
David Garcia4fee80e2020-05-13 12:18:38 +0200119 entity: ModelEntity,
120 progress_timeout: float = 3600,
121 total_timeout: float = 3600,
122 db_dict: dict = None,
123 n2vc: N2VCConnector = None,
David Garciaeb8943a2021-04-12 12:07:37 +0200124 vca_id: str = None,
David Garcia4fee80e2020-05-13 12:18:38 +0200125 ):
126 """
127 Wait for entity to reach its final state.
128
129 :param: model: Model to observe
130 :param: entity: Entity object
131 :param: progress_timeout: Maximum time between two updates in the model
132 :param: total_timeout: Timeout for the entity to be active
133 :param: db_dict: Dictionary with data of the DB to write the updates
134 :param: n2vc: N2VC Connector objector
David Garciaeb8943a2021-04-12 12:07:37 +0200135 :param: vca_id: VCA ID
David Garcia4fee80e2020-05-13 12:18:38 +0200136
137 :raises: asyncio.TimeoutError when timeout reaches
138 """
139
140 if progress_timeout is None:
141 progress_timeout = 3600.0
142 if total_timeout is None:
143 total_timeout = 3600.0
144
David Garciac38a6962020-09-16 13:31:33 +0200145 entity_type = entity.entity_type
146 if entity_type not in ["application", "action", "machine"]:
147 raise EntityInvalidException("Unknown entity type: {}".format(entity_type))
David Garcia4fee80e2020-05-13 12:18:38 +0200148
149 # Coroutine to wait until the entity reaches the final state
150 wait_for_entity = asyncio.ensure_future(
151 asyncio.wait_for(
David Garciac3441172021-03-10 11:50:38 +0100152 model.block_until(lambda: entity_ready(entity)),
153 timeout=total_timeout,
David Garcia4fee80e2020-05-13 12:18:38 +0200154 )
155 )
156
157 # Coroutine to watch the model for changes (and write them to DB)
158 watcher = asyncio.ensure_future(
159 JujuModelWatcher.model_watcher(
160 model,
161 entity_id=entity.entity_id,
162 entity_type=entity_type,
163 timeout=progress_timeout,
164 db_dict=db_dict,
165 n2vc=n2vc,
David Garciaeb8943a2021-04-12 12:07:37 +0200166 vca_id=vca_id,
David Garcia4fee80e2020-05-13 12:18:38 +0200167 )
168 )
169
170 tasks = [wait_for_entity, watcher]
171 try:
172 # Execute tasks, and stop when the first is finished
173 # The watcher task won't never finish (unless it timeouts)
174 await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
David Garcia4fee80e2020-05-13 12:18:38 +0200175 finally:
176 # Cancel tasks
177 for task in tasks:
178 task.cancel()
179
180 @staticmethod
181 async def model_watcher(
182 model: Model,
183 entity_id: str,
David Garciac38a6962020-09-16 13:31:33 +0200184 entity_type: str,
David Garcia4fee80e2020-05-13 12:18:38 +0200185 timeout: float,
186 db_dict: dict = None,
187 n2vc: N2VCConnector = None,
David Garciaeb8943a2021-04-12 12:07:37 +0200188 vca_id: str = None,
David Garcia4fee80e2020-05-13 12:18:38 +0200189 ):
190 """
191 Observes the changes related to an specific entity in a model
192
193 :param: model: Model to observe
194 :param: entity_id: ID of the entity to be observed
David Garciac38a6962020-09-16 13:31:33 +0200195 :param: entity_type: Entity Type (p.e. "application", "machine, and "action")
David Garcia4fee80e2020-05-13 12:18:38 +0200196 :param: timeout: Maximum time between two updates in the model
197 :param: db_dict: Dictionary with data of the DB to write the updates
198 :param: n2vc: N2VC Connector objector
David Garciaeb8943a2021-04-12 12:07:37 +0200199 :param: vca_id: VCA ID
David Garcia4fee80e2020-05-13 12:18:38 +0200200
201 :raises: asyncio.TimeoutError when timeout reaches
202 """
203
204 allwatcher = client.AllWatcherFacade.from_connection(model.connection())
205
206 # Genenerate array with entity types to listen
207 entity_types = (
David Garciac38a6962020-09-16 13:31:33 +0200208 [entity_type, "unit"]
209 if entity_type == "application" # TODO: Add "action" too
David Garcia4fee80e2020-05-13 12:18:38 +0200210 else [entity_type]
211 )
212
213 # Get time when it should timeout
214 timeout_end = time.time() + timeout
215
David Garcia2f66c4d2020-06-19 11:40:18 +0200216 try:
217 while True:
218 change = await allwatcher.Next()
219 for delta in change.deltas:
220 write = False
221 delta_entity = None
David Garcia4fee80e2020-05-13 12:18:38 +0200222
David Garcia2f66c4d2020-06-19 11:40:18 +0200223 # Get delta EntityType
David Garciac38a6962020-09-16 13:31:33 +0200224 delta_entity = delta.entity
David Garcia4fee80e2020-05-13 12:18:38 +0200225
David Garcia2f66c4d2020-06-19 11:40:18 +0200226 if delta_entity in entity_types:
227 # Get entity id
David Garciac38a6962020-09-16 13:31:33 +0200228 if entity_type == "application":
David Garcia2f66c4d2020-06-19 11:40:18 +0200229 id = (
230 delta.data["application"]
David Garciac38a6962020-09-16 13:31:33 +0200231 if delta_entity == "unit"
David Garcia2f66c4d2020-06-19 11:40:18 +0200232 else delta.data["name"]
233 )
234 else:
235 id = delta.data["id"]
236
237 # Write if the entity id match
238 write = True if id == entity_id else False
239
240 # Update timeout
241 timeout_end = time.time() + timeout
David Garciac38a6962020-09-16 13:31:33 +0200242 (
243 status,
244 status_message,
245 vca_status,
246 ) = JujuModelWatcher.get_status(delta)
David Garcia4fee80e2020-05-13 12:18:38 +0200247
David Garcia2f66c4d2020-06-19 11:40:18 +0200248 if write and n2vc is not None and db_dict:
249 # Write status to DB
250 status = n2vc.osm_status(delta_entity, status)
251 await n2vc.write_app_status_to_db(
252 db_dict=db_dict,
253 status=status,
254 detailed_status=status_message,
255 vca_status=vca_status,
David Garciac38a6962020-09-16 13:31:33 +0200256 entity_type=delta_entity,
David Garciaeb8943a2021-04-12 12:07:37 +0200257 vca_id=vca_id,
David Garcia2f66c4d2020-06-19 11:40:18 +0200258 )
259 # Check if timeout
260 if time.time() > timeout_end:
261 raise asyncio.TimeoutError()
262 except ConnectionClosed:
263 pass
264 # This is expected to happen when the
265 # entity reaches its final state, because
266 # the model connection is closed afterwards
David Garcia4fee80e2020-05-13 12:18:38 +0200267
268 @staticmethod
David Garciac38a6962020-09-16 13:31:33 +0200269 def get_status(delta: Delta) -> (str, str, str):
David Garcia4fee80e2020-05-13 12:18:38 +0200270 """
271 Get status from delta
272
273 :param: delta: Delta generated by the allwatcher
David Garciac38a6962020-09-16 13:31:33 +0200274 :param: entity_type: Entity Type (p.e. "application", "machine, and "action")
David Garcia4fee80e2020-05-13 12:18:38 +0200275
276 :return (status, message, vca_status)
277 """
David Garciac38a6962020-09-16 13:31:33 +0200278 if delta.entity == "machine":
David Garcia4fee80e2020-05-13 12:18:38 +0200279 return (
280 delta.data["agent-status"]["current"],
281 delta.data["instance-status"]["message"],
282 delta.data["instance-status"]["current"],
283 )
David Garciac38a6962020-09-16 13:31:33 +0200284 elif delta.entity == "action":
David Garcia4fee80e2020-05-13 12:18:38 +0200285 return (
286 delta.data["status"],
287 delta.data["status"],
288 delta.data["status"],
289 )
David Garciac38a6962020-09-16 13:31:33 +0200290 elif delta.entity == "application":
David Garcia4fee80e2020-05-13 12:18:38 +0200291 return (
292 delta.data["status"]["current"],
293 delta.data["status"]["message"],
294 delta.data["status"]["current"],
295 )
David Garciac38a6962020-09-16 13:31:33 +0200296 elif delta.entity == "unit":
David Garcia4fee80e2020-05-13 12:18:38 +0200297 return (
298 delta.data["workload-status"]["current"],
299 delta.data["workload-status"]["message"],
300 delta.data["workload-status"]["current"],
301 )