| Adam Israel | 1a15d1c | 2017-10-23 12:00:49 -0400 | [diff] [blame] | 1 | # Copyright 2016 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 | |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 15 | import asyncio |
| 16 | import logging |
| 17 | |
| 18 | from . import model |
| 19 | from .client import client |
| 20 | from .errors import JujuError |
| 21 | from .placement import parse as parse_placement |
| 22 | |
| 23 | log = logging.getLogger(__name__) |
| 24 | |
| 25 | |
| 26 | class Application(model.ModelEntity): |
| 27 | @property |
| 28 | def _unit_match_pattern(self): |
| 29 | return r'^{}.*$'.format(self.entity_id) |
| 30 | |
| 31 | def on_unit_add(self, callable_): |
| 32 | """Add a "unit added" observer to this entity, which will be called |
| 33 | whenever a unit is added to this application. |
| 34 | |
| 35 | """ |
| 36 | self.model.add_observer( |
| 37 | callable_, 'unit', 'add', self._unit_match_pattern) |
| 38 | |
| 39 | def on_unit_remove(self, callable_): |
| 40 | """Add a "unit removed" observer to this entity, which will be called |
| 41 | whenever a unit is removed from this application. |
| 42 | |
| 43 | """ |
| 44 | self.model.add_observer( |
| 45 | callable_, 'unit', 'remove', self._unit_match_pattern) |
| 46 | |
| 47 | @property |
| 48 | def units(self): |
| 49 | return [ |
| 50 | unit for unit in self.model.units.values() |
| 51 | if unit.application == self.name |
| 52 | ] |
| 53 | |
| 54 | @property |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 55 | def relations(self): |
| 56 | return [rel for rel in self.model.relations if rel.matches(self.name)] |
| 57 | |
| 58 | def related_applications(self, endpoint_name=None): |
| 59 | apps = {} |
| 60 | for rel in self.relations: |
| 61 | if rel.is_peer: |
| 62 | local_ep, remote_ep = rel.endpoints[0] |
| 63 | else: |
| 64 | def is_us(ep): |
| 65 | return ep.application.name == self.name |
| 66 | local_ep, remote_ep = sorted(rel.endpoints, key=is_us) |
| 67 | if endpoint_name is not None and endpoint_name != local_ep.name: |
| 68 | continue |
| 69 | apps[remote_ep.application.name] = remote_ep.application |
| 70 | return apps |
| 71 | |
| 72 | @property |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 73 | def status(self): |
| 74 | """Get the application status, as set by the charm's leader. |
| 75 | |
| 76 | """ |
| 77 | return self.safe_data['status']['current'] |
| 78 | |
| 79 | @property |
| 80 | def status_message(self): |
| 81 | """Get the application status message, as set by the charm's leader. |
| 82 | |
| 83 | """ |
| 84 | return self.safe_data['status']['message'] |
| 85 | |
| 86 | @property |
| 87 | def tag(self): |
| 88 | return 'application-%s' % self.name |
| 89 | |
| 90 | async def add_relation(self, local_relation, remote_relation): |
| 91 | """Add a relation to another application. |
| 92 | |
| 93 | :param str local_relation: Name of relation on this application |
| 94 | :param str remote_relation: Name of relation on the other |
| 95 | application in the form '<application>[:<relation_name>]' |
| 96 | |
| 97 | """ |
| 98 | if ':' not in local_relation: |
| 99 | local_relation = '{}:{}'.format(self.name, local_relation) |
| 100 | |
| 101 | return await self.model.add_relation(local_relation, remote_relation) |
| 102 | |
| 103 | async def add_unit(self, count=1, to=None): |
| 104 | """Add one or more units to this application. |
| 105 | |
| 106 | :param int count: Number of units to add |
| 107 | :param str to: Placement directive, e.g.:: |
| 108 | '23' - machine 23 |
| 109 | 'lxc:7' - new lxc container on machine 7 |
| 110 | '24/lxc/3' - lxc container 3 or machine 24 |
| 111 | |
| 112 | If None, a new machine is provisioned. |
| 113 | |
| 114 | """ |
| 115 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 116 | |
| 117 | log.debug( |
| 118 | 'Adding %s unit%s to %s', |
| 119 | count, '' if count == 1 else 's', self.name) |
| 120 | |
| 121 | result = await app_facade.AddUnits( |
| 122 | application=self.name, |
| 123 | placement=parse_placement(to) if to else None, |
| 124 | num_units=count, |
| 125 | ) |
| 126 | |
| 127 | return await asyncio.gather(*[ |
| 128 | asyncio.ensure_future(self.model._wait_for_new('unit', unit_id)) |
| 129 | for unit_id in result.units |
| 130 | ]) |
| 131 | |
| 132 | add_units = add_unit |
| 133 | |
| 134 | def allocate(self, budget, value): |
| 135 | """Allocate budget to this application. |
| 136 | |
| 137 | :param str budget: Name of budget |
| 138 | :param int value: Budget limit |
| 139 | |
| 140 | """ |
| 141 | raise NotImplementedError() |
| 142 | |
| 143 | def attach(self, resource_name, file_path): |
| 144 | """Upload a file as a resource for this application. |
| 145 | |
| 146 | :param str resource: Name of the resource |
| 147 | :param str file_path: Path to the file to upload |
| 148 | |
| 149 | """ |
| 150 | raise NotImplementedError() |
| 151 | |
| 152 | def collect_metrics(self): |
| 153 | """Collect metrics on this application. |
| 154 | |
| 155 | """ |
| 156 | raise NotImplementedError() |
| 157 | |
| 158 | async def destroy_relation(self, local_relation, remote_relation): |
| 159 | """Remove a relation to another application. |
| 160 | |
| 161 | :param str local_relation: Name of relation on this application |
| 162 | :param str remote_relation: Name of relation on the other |
| 163 | application in the form '<application>[:<relation_name>]' |
| 164 | |
| 165 | """ |
| 166 | if ':' not in local_relation: |
| 167 | local_relation = '{}:{}'.format(self.name, local_relation) |
| 168 | |
| 169 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 170 | |
| 171 | log.debug( |
| 172 | 'Destroying relation %s <-> %s', local_relation, remote_relation) |
| 173 | |
| 174 | return await app_facade.DestroyRelation([ |
| 175 | local_relation, remote_relation]) |
| 176 | remove_relation = destroy_relation |
| 177 | |
| 178 | async def destroy_unit(self, *unit_names): |
| 179 | """Destroy units by name. |
| 180 | |
| 181 | """ |
| 182 | return await self.model.destroy_units(*unit_names) |
| 183 | destroy_units = destroy_unit |
| 184 | |
| 185 | async def destroy(self): |
| 186 | """Remove this application from the model. |
| 187 | |
| 188 | """ |
| 189 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 190 | |
| 191 | log.debug( |
| 192 | 'Destroying %s', self.name) |
| 193 | |
| 194 | return await app_facade.Destroy(self.name) |
| 195 | remove = destroy |
| 196 | |
| 197 | async def expose(self): |
| 198 | """Make this application publicly available over the network. |
| 199 | |
| 200 | """ |
| 201 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 202 | |
| 203 | log.debug( |
| 204 | 'Exposing %s', self.name) |
| 205 | |
| 206 | return await app_facade.Expose(self.name) |
| 207 | |
| 208 | async def get_config(self): |
| 209 | """Return the configuration settings dict for this application. |
| 210 | |
| 211 | """ |
| 212 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 213 | |
| 214 | log.debug( |
| 215 | 'Getting config for %s', self.name) |
| 216 | |
| 217 | return (await app_facade.Get(self.name)).config |
| 218 | |
| 219 | async def get_constraints(self): |
| 220 | """Return the machine constraints dict for this application. |
| 221 | |
| 222 | """ |
| 223 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 224 | |
| 225 | log.debug( |
| 226 | 'Getting constraints for %s', self.name) |
| 227 | |
| 228 | result = (await app_facade.Get(self.name)).constraints |
| 229 | return vars(result) if result else result |
| 230 | |
| Adam Israel | b094366 | 2018-08-02 15:32:00 -0400 | [diff] [blame] | 231 | async def get_actions(self, schema=False): |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 232 | """Get actions defined for this application. |
| 233 | |
| 234 | :param bool schema: Return the full action schema |
| Adam Israel | b094366 | 2018-08-02 15:32:00 -0400 | [diff] [blame] | 235 | :return dict: The charms actions, empty dict if none are defined. |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 236 | """ |
| Adam Israel | b094366 | 2018-08-02 15:32:00 -0400 | [diff] [blame] | 237 | actions = {} |
| 238 | entity = [{"tag": self.tag}] |
| 239 | action_facade = client.ActionFacade.from_connection(self.connection) |
| 240 | results = ( |
| 241 | await action_facade.ApplicationsCharmsActions(entity)).results |
| 242 | for result in results: |
| 243 | if result.application_tag == self.tag and result.actions: |
| 244 | actions = result.actions |
| 245 | break |
| 246 | if not schema: |
| 247 | actions = {k: v['description'] for k, v in actions.items()} |
| 248 | return actions |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 249 | |
| 250 | def get_resources(self, details=False): |
| 251 | """Return resources for this application. |
| 252 | |
| 253 | :param bool details: Include detailed info about resources used by each |
| 254 | unit |
| 255 | |
| 256 | """ |
| 257 | raise NotImplementedError() |
| 258 | |
| 259 | async def run(self, command, timeout=None): |
| 260 | """Run command on all units for this application. |
| 261 | |
| 262 | :param str command: The command to run |
| 263 | :param int timeout: Time to wait before command is considered failed |
| 264 | |
| 265 | """ |
| 266 | action = client.ActionFacade.from_connection(self.connection) |
| 267 | |
| 268 | log.debug( |
| 269 | 'Running `%s` on all units of %s', command, self.name) |
| 270 | |
| 271 | # TODO this should return a list of Actions |
| 272 | return await action.Run( |
| 273 | [self.name], |
| 274 | command, |
| 275 | [], |
| 276 | timeout, |
| 277 | [], |
| 278 | ) |
| 279 | |
| 280 | async def set_annotations(self, annotations): |
| 281 | """Set annotations on this application. |
| 282 | |
| 283 | :param annotations map[string]string: the annotations as key/value |
| 284 | pairs. |
| 285 | |
| 286 | """ |
| 287 | log.debug('Updating annotations on application %s', self.name) |
| 288 | |
| 289 | self.ann_facade = client.AnnotationsFacade.from_connection( |
| 290 | self.connection) |
| 291 | |
| 292 | ann = client.EntityAnnotations( |
| 293 | entity=self.tag, |
| 294 | annotations=annotations, |
| 295 | ) |
| 296 | return await self.ann_facade.Set([ann]) |
| 297 | |
| Adam Israel | b094366 | 2018-08-02 15:32:00 -0400 | [diff] [blame] | 298 | async def set_config(self, config): |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 299 | """Set configuration options for this application. |
| 300 | |
| 301 | :param config: Dict of configuration to set |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 302 | """ |
| 303 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 304 | |
| 305 | log.debug( |
| 306 | 'Setting config for %s: %s', self.name, config) |
| 307 | |
| 308 | return await app_facade.Set(self.name, config) |
| 309 | |
| Adam Israel | b094366 | 2018-08-02 15:32:00 -0400 | [diff] [blame] | 310 | async def reset_config(self, to_default): |
| 311 | """ |
| 312 | Restore application config to default values. |
| 313 | |
| 314 | :param list to_default: A list of config options to be reset to their default value. |
| 315 | """ |
| 316 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 317 | |
| 318 | log.debug( |
| 319 | 'Restoring default config for %s: %s', self.name, to_default) |
| 320 | |
| 321 | return await app_facade.Unset(self.name, to_default) |
| 322 | |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 323 | async def set_constraints(self, constraints): |
| 324 | """Set machine constraints for this application. |
| 325 | |
| 326 | :param dict constraints: Dict of machine constraints |
| 327 | |
| 328 | """ |
| 329 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 330 | |
| 331 | log.debug( |
| 332 | 'Setting constraints for %s: %s', self.name, constraints) |
| 333 | |
| 334 | return await app_facade.SetConstraints(self.name, constraints) |
| 335 | |
| 336 | def set_meter_status(self, status, info=None): |
| 337 | """Set the meter status on this status. |
| 338 | |
| 339 | :param str status: Meter status, e.g. 'RED', 'AMBER' |
| 340 | :param str info: Extra info message |
| 341 | |
| 342 | """ |
| 343 | raise NotImplementedError() |
| 344 | |
| 345 | def set_plan(self, plan_name): |
| 346 | """Set the plan for this application, effective immediately. |
| 347 | |
| 348 | :param str plan_name: Name of plan |
| 349 | |
| 350 | """ |
| 351 | raise NotImplementedError() |
| 352 | |
| 353 | async def unexpose(self): |
| 354 | """Remove public availability over the network for this application. |
| 355 | |
| 356 | """ |
| 357 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 358 | |
| 359 | log.debug( |
| 360 | 'Unexposing %s', self.name) |
| 361 | |
| 362 | return await app_facade.Unexpose(self.name) |
| 363 | |
| 364 | def update_allocation(self, allocation): |
| 365 | """Update existing allocation for this application. |
| 366 | |
| 367 | :param int allocation: The allocation to set |
| 368 | |
| 369 | """ |
| 370 | raise NotImplementedError() |
| 371 | |
| 372 | async def upgrade_charm( |
| 373 | self, channel=None, force_series=False, force_units=False, |
| 374 | path=None, resources=None, revision=None, switch=None): |
| 375 | """Upgrade the charm for this application. |
| 376 | |
| 377 | :param str channel: Channel to use when getting the charm from the |
| 378 | charm store, e.g. 'development' |
| 379 | :param bool force_series: Upgrade even if series of deployed |
| 380 | application is not supported by the new charm |
| 381 | :param bool force_units: Upgrade all units immediately, even if in |
| 382 | error state |
| 383 | :param str path: Uprade to a charm located at path |
| 384 | :param dict resources: Dictionary of resource name/filepath pairs |
| 385 | :param int revision: Explicit upgrade revision |
| 386 | :param str switch: Crossgrade charm url |
| 387 | |
| 388 | """ |
| 389 | # TODO: Support local upgrades |
| 390 | if path is not None: |
| 391 | raise NotImplementedError("path option is not implemented") |
| 392 | if resources is not None: |
| 393 | raise NotImplementedError("resources option is not implemented") |
| 394 | |
| 395 | if switch is not None and revision is not None: |
| 396 | raise ValueError("switch and revision are mutually exclusive") |
| 397 | |
| 398 | client_facade = client.ClientFacade.from_connection(self.connection) |
| Adam Israel | 1a15d1c | 2017-10-23 12:00:49 -0400 | [diff] [blame] | 399 | resources_facade = client.ResourcesFacade.from_connection( |
| 400 | self.connection) |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 401 | app_facade = client.ApplicationFacade.from_connection(self.connection) |
| 402 | |
| Adam Israel | 1a15d1c | 2017-10-23 12:00:49 -0400 | [diff] [blame] | 403 | charmstore = self.model.charmstore |
| 404 | charmstore_entity = None |
| 405 | |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 406 | if switch is not None: |
| 407 | charm_url = switch |
| 408 | if not charm_url.startswith('cs:'): |
| 409 | charm_url = 'cs:' + charm_url |
| 410 | else: |
| 411 | charm_url = self.data['charm-url'] |
| 412 | charm_url = charm_url.rpartition('-')[0] |
| 413 | if revision is not None: |
| 414 | charm_url = "%s-%d" % (charm_url, revision) |
| 415 | else: |
| Adam Israel | 1a15d1c | 2017-10-23 12:00:49 -0400 | [diff] [blame] | 416 | charmstore_entity = await charmstore.entity(charm_url, |
| 417 | channel=channel) |
| 418 | charm_url = charmstore_entity['Id'] |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 419 | |
| 420 | if charm_url == self.data['charm-url']: |
| 421 | raise JujuError('already running charm "%s"' % charm_url) |
| 422 | |
| Adam Israel | 1a15d1c | 2017-10-23 12:00:49 -0400 | [diff] [blame] | 423 | # Update charm |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 424 | await client_facade.AddCharm( |
| 425 | url=charm_url, |
| 426 | channel=channel |
| 427 | ) |
| 428 | |
| Adam Israel | 1a15d1c | 2017-10-23 12:00:49 -0400 | [diff] [blame] | 429 | # Update resources |
| 430 | if not charmstore_entity: |
| 431 | charmstore_entity = await charmstore.entity(charm_url, |
| 432 | channel=channel) |
| 433 | store_resources = charmstore_entity['Meta']['resources'] |
| 434 | |
| 435 | request_data = [client.Entity(self.tag)] |
| 436 | response = await resources_facade.ListResources(request_data) |
| 437 | existing_resources = { |
| 438 | resource.name: resource |
| 439 | for resource in response.results[0].resources |
| 440 | } |
| 441 | |
| 442 | resources_to_update = [ |
| 443 | resource for resource in store_resources |
| 444 | if resource['Name'] not in existing_resources or |
| 445 | existing_resources[resource['Name']].origin != 'upload' |
| 446 | ] |
| 447 | |
| 448 | if resources_to_update: |
| 449 | request_data = [ |
| 450 | client.CharmResource( |
| 451 | description=resource.get('Description'), |
| 452 | fingerprint=resource['Fingerprint'], |
| 453 | name=resource['Name'], |
| 454 | path=resource['Path'], |
| 455 | revision=resource['Revision'], |
| 456 | size=resource['Size'], |
| 457 | type_=resource['Type'], |
| 458 | origin='store', |
| 459 | ) for resource in resources_to_update |
| 460 | ] |
| 461 | response = await resources_facade.AddPendingResources( |
| 462 | self.tag, |
| 463 | charm_url, |
| 464 | request_data |
| 465 | ) |
| 466 | pending_ids = response.pending_ids |
| 467 | resource_ids = { |
| 468 | resource['Name']: id |
| 469 | for resource, id in zip(resources_to_update, pending_ids) |
| 470 | } |
| 471 | else: |
| 472 | resource_ids = None |
| 473 | |
| 474 | # Update application |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 475 | await app_facade.SetCharm( |
| 476 | application=self.entity_id, |
| 477 | channel=channel, |
| 478 | charm_url=charm_url, |
| 479 | config_settings=None, |
| 480 | config_settings_yaml=None, |
| 481 | force_series=force_series, |
| 482 | force_units=force_units, |
| Adam Israel | 1a15d1c | 2017-10-23 12:00:49 -0400 | [diff] [blame] | 483 | resource_ids=resource_ids, |
| Adam Israel | dcdf82b | 2017-08-15 15:26:43 -0400 | [diff] [blame] | 484 | storage_constraints=None |
| 485 | ) |
| 486 | |
| 487 | await self.model.block_until( |
| 488 | lambda: self.data['charm-url'] == charm_url |
| 489 | ) |
| 490 | |
| 491 | async def get_metrics(self): |
| 492 | """Get metrics for this application's units. |
| 493 | |
| 494 | :return: Dictionary of unit_name:metrics |
| 495 | |
| 496 | """ |
| 497 | return await self.model.get_metrics(self.tag) |