Clean up deploy example
[osm/N2VC.git] / juju / model.py
1 import logging
2
3 from .client import client
4 from .client import watcher
5 from .delta import get_entity_delta
6
7 log = logging.getLogger(__name__)
8
9
10 class ModelObserver(object):
11 def __call__(self, delta, old, new, model):
12 if old is None and new is not None:
13 type_ = 'add'
14 else:
15 type_ = delta.type
16 handler_name = 'on_{}_{}'.format(delta.entity, type_)
17 method = getattr(self, handler_name, self.on_change)
18 log.debug(
19 'Model changed: %s %s %s',
20 delta.entity, delta.type, delta.get_id())
21 method(delta, old, new, model)
22
23 def on_change(self, delta, old, new, model):
24 pass
25
26
27 class ModelEntity(object):
28 """An object in the Model tree"""
29
30 def __init__(self, data, model):
31 """Initialize a new entity
32
33 :param data: dict of data from a watcher delta
34 :param model: The model instance in whose object tree this
35 entity resides
36
37 """
38 self.data = data
39 self.model = model
40 self.connection = model.connection
41
42 def __getattr__(self, name):
43 return self.data[name]
44
45
46 class Model(object):
47 def __init__(self, connection):
48 """Instantiate a new connected Model.
49
50 :param connection: `juju.client.connection.Connection` instance
51
52 """
53 self.connection = connection
54 self.observers = set()
55 self.state = dict()
56
57 @property
58 def applications(self):
59 return self.state.get('application', {})
60
61 @property
62 def units(self):
63 return self.state.get('unit', {})
64
65 def add_observer(self, callable_):
66 """Register an "on-model-change" callback
67
68 Once a watch is started (Model.watch() is called), ``callable_``
69 will be called each time the model changes. callable_ should
70 accept the following positional arguments:
71
72 delta - An instance of :class:`juju.delta.EntityDelta`
73 containing the raw delta data recv'd from the Juju
74 websocket.
75
76 old_obj - If the delta modifies an existing object in the model,
77 old_obj will be a copy of that object, as it was before the
78 delta was applied. Will be None if the delta creates a new
79 entity in the model.
80
81 new_obj - A copy of the new or updated object, after the delta
82 is applied. Will be None if the delta removes an entity
83 from the model.
84
85 model - The :class:`Model` itself.
86
87 """
88 self.observers.add(callable_)
89
90 async def watch(self):
91 """Start an asynchronous watch against this model.
92
93 See :meth:`add_observer` to register an onchange callback.
94
95 """
96 self._watching = True
97 allwatcher = watcher.AllWatcher()
98 allwatcher.connect(await self.connection.clone())
99 while True:
100 results = await allwatcher.Next()
101 for delta in results.deltas:
102 delta = get_entity_delta(delta)
103 old_obj, new_obj = self._apply_delta(delta)
104 self._notify_observers(delta, old_obj, new_obj)
105
106 def _apply_delta(self, delta):
107 """Apply delta to our model state and return the a copy of the
108 affected object as it was before and after the update, e.g.:
109
110 old_obj, new_obj = self._apply_delta(delta)
111
112 old_obj may be None if the delta is for the creation of a new object,
113 e.g. a new application or unit is deployed.
114
115 new_obj may be None if no object was created or updated, or if an
116 object was deleted as a result of the delta being applied.
117
118 """
119 old_obj, new_obj = None, None
120
121 if (delta.entity in self.state and
122 delta.get_id() in self.state[delta.entity]):
123 old_obj = self.state[delta.entity][delta.get_id()]
124 if delta.type == 'remove':
125 del self.state[delta.entity][delta.get_id()]
126 return old_obj, new_obj
127
128 new_obj = self.state.setdefault(delta.entity, {})[delta.get_id()] = (
129 self._create_model_entity(delta))
130
131 return old_obj, new_obj
132
133 def _create_model_entity(self, delta):
134 """Return an object instance representing the entity created or
135 updated by ``delta``
136
137 """
138 entity_class = delta.get_entity_class()
139 return entity_class(delta.data, self)
140
141 def _notify_observers(self, delta, old_obj, new_obj):
142 """Call observing callbacks, notifying them of a change in model state
143
144 :param delta: The raw change from the watcher
145 (:class:`juju.client.overrides.Delta`)
146 :param old_obj: The object in the model that this delta updates.
147 May be None.
148 :param new_obj: The object in the model that is created or updated
149 by applying this delta.
150
151 """
152 for o in self.observers:
153 o(delta, old_obj, new_obj, self)
154
155 def add_machine(
156 self, spec=None, constraints=None, disks=None, series=None,
157 count=1):
158 """Start a new, empty machine and optionally a container, or add a
159 container to a machine.
160
161 :param str spec: Machine specification
162 Examples::
163
164 (None) - starts a new machine
165 'lxc' - starts a new machine with on lxc container
166 'lxc:4' - starts a new lxc container on machine 4
167 'ssh:user@10.10.0.3' - manually provisions a machine with ssh
168 'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS
169 'maas2.name' - acquire machine maas2.name on MAAS
170 :param constraints: Machine constraints
171 :type constraints: :class:`juju.Constraints`
172 :param list disks: List of disk :class:`constraints <juju.Constraints>`
173 :param str series: Series
174 :param int count: Number of machines to deploy
175
176 Supported container types are: lxc, lxd, kvm
177
178 When deploying a container to an existing machine, constraints cannot
179 be used.
180
181 """
182 pass
183 add_machines = add_machine
184
185 def add_relation(self, relation1, relation2):
186 """Add a relation between two services.
187
188 :param str relation1: '<service>[:<relation_name>]'
189 :param str relation2: '<service>[:<relation_name>]'
190
191 """
192 pass
193
194 def add_space(self, name, *cidrs):
195 """Add a new network space.
196
197 Adds a new space with the given name and associates the given
198 (optional) list of existing subnet CIDRs with it.
199
200 :param str name: Name of the space
201 :param \*cidrs: Optional list of existing subnet CIDRs
202
203 """
204 pass
205
206 def add_ssh_key(self, key):
207 """Add a public SSH key to this model.
208
209 :param str key: The public ssh key
210
211 """
212 pass
213 add_ssh_keys = add_ssh_key
214
215 def add_subnet(self, cidr_or_id, space, *zones):
216 """Add an existing subnet to this model.
217
218 :param str cidr_or_id: CIDR or provider ID of the existing subnet
219 :param str space: Network space with which to associate
220 :param str \*zones: Zone(s) in which the subnet resides
221
222 """
223 pass
224
225 def get_backups(self):
226 """Retrieve metadata for backups in this model.
227
228 """
229 pass
230
231 def block(self, *commands):
232 """Add a new block to this model.
233
234 :param str \*commands: The commands to block. Valid values are
235 'all-changes', 'destroy-model', 'remove-object'
236
237 """
238 pass
239
240 def get_blocks(self):
241 """List blocks for this model.
242
243 """
244 pass
245
246 def get_cached_images(self, arch=None, kind=None, series=None):
247 """Return a list of cached OS images.
248
249 :param str arch: Filter by image architecture
250 :param str kind: Filter by image kind, e.g. 'lxd'
251 :param str series: Filter by image series, e.g. 'xenial'
252
253 """
254 pass
255
256 def create_backup(self, note=None, no_download=False):
257 """Create a backup of this model.
258
259 :param str note: A note to store with the backup
260 :param bool no_download: Do not download the backup archive
261 :return str: Path to downloaded archive
262
263 """
264 pass
265
266 def create_storage_pool(self, name, provider_type, **pool_config):
267 """Create or define a storage pool.
268
269 :param str name: Name to give the storage pool
270 :param str provider_type: Pool provider type
271 :param \*\*pool_config: key/value pool configuration pairs
272
273 """
274 pass
275
276 def debug_log(
277 self, no_tail=False, exclude_module=None, include_module=None,
278 include=None, level=None, limit=0, lines=10, replay=False,
279 exclude=None):
280 """Get log messages for this model.
281
282 :param bool no_tail: Stop after returning existing log messages
283 :param list exclude_module: Do not show log messages for these logging
284 modules
285 :param list include_module: Only show log messages for these logging
286 modules
287 :param list include: Only show log messages for these entities
288 :param str level: Log level to show, valid options are 'TRACE',
289 'DEBUG', 'INFO', 'WARNING', 'ERROR,
290 :param int limit: Return this many of the most recent (possibly
291 filtered) lines are shown
292 :param int lines: Yield this many of the most recent lines, and keep
293 yielding
294 :param bool replay: Yield the entire log, and keep yielding
295 :param list exclude: Do not show log messages for these entities
296
297 """
298 pass
299
300 async def deploy(
301 self, entity_url, service_name=None, bind=None, budget=None,
302 channel=None, config=None, constraints=None, force=False,
303 num_units=1, plan=None, resources=None, series=None, storage=None,
304 to=None):
305 """Deploy a new service or bundle.
306
307 :param str entity_url: Charm or bundle url
308 :param str service_name: Name to give the service
309 :param dict bind: <charm endpoint>:<network space> pairs
310 :param dict budget: <budget name>:<limit> pairs
311 :param str channel: Charm store channel from which to retrieve
312 the charm or bundle, e.g. 'development'
313 :param dict config: Charm configuration dictionary
314 :param constraints: Service constraints
315 :type constraints: :class:`juju.Constraints`
316 :param bool force: Allow charm to be deployed to a machine running
317 an unsupported series
318 :param int num_units: Number of units to deploy
319 :param str plan: Plan under which to deploy charm
320 :param dict resources: <resource name>:<file path> pairs
321 :param str series: Series on which to deploy
322 :param dict storage: Storage constraints TODO how do these look?
323 :param str to: Placement directive, e.g.::
324
325 '23' - machine 23
326 'lxc:7' - new lxc container on machine 7
327 '24/lxc/3' - lxc container 3 or machine 24
328
329 If None, a new machine is provisioned.
330
331
332 TODO::
333
334 - entity_url must have a revision; look up latest automatically if
335 not provided by caller
336 - service_name is required; fill this in automatically if not
337 provided by caller
338 - series is required; how do we pick a default?
339
340 """
341 if constraints:
342 constraints = client.Value(**constraints)
343
344 if to:
345 placement = [
346 client.Placement(**p) for p in to
347 ]
348 else:
349 placement = []
350
351 if storage:
352 storage = {
353 k: client.Constraints(**v)
354 for k, v in storage.items()
355 }
356
357 app_facade = client.ApplicationFacade()
358 client_facade = client.ClientFacade()
359 app_facade.connect(self.connection)
360 client_facade.connect(self.connection)
361
362 log.debug(
363 'Deploying %s', entity_url)
364
365 await client_facade.AddCharm(channel, entity_url)
366 app = client.ApplicationDeploy(
367 application=service_name,
368 channel=channel,
369 charm_url=entity_url,
370 config=config,
371 constraints=constraints,
372 endpoint_bindings=bind,
373 num_units=num_units,
374 placement=placement,
375 resources=resources,
376 series=series,
377 storage=storage,
378 )
379
380 return await app_facade.Deploy([app])
381
382 def destroy(self):
383 """Terminate all machines and resources for this model.
384
385 """
386 pass
387
388 def get_backup(self, archive_id):
389 """Download a backup archive file.
390
391 :param str archive_id: The id of the archive to download
392 :return str: Path to the archive file
393
394 """
395 pass
396
397 def enable_ha(
398 self, num_controllers=0, constraints=None, series=None, to=None):
399 """Ensure sufficient controllers exist to provide redundancy.
400
401 :param int num_controllers: Number of controllers to make available
402 :param constraints: Constraints to apply to the controller machines
403 :type constraints: :class:`juju.Constraints`
404 :param str series: Series of the controller machines
405 :param list to: Placement directives for controller machines, e.g.::
406
407 '23' - machine 23
408 'lxc:7' - new lxc container on machine 7
409 '24/lxc/3' - lxc container 3 or machine 24
410
411 If None, a new machine is provisioned.
412
413 """
414 pass
415
416 def get_config(self):
417 """Return the configuration settings for this model.
418
419 """
420 pass
421
422 def get_constraints(self):
423 """Return the machine constraints for this model.
424
425 """
426 pass
427
428 def grant(self, username, acl='read'):
429 """Grant a user access to this model.
430
431 :param str username: Username
432 :param str acl: Access control ('read' or 'write')
433
434 """
435 pass
436
437 def import_ssh_key(self, identity):
438 """Add a public SSH key from a trusted indentity source to this model.
439
440 :param str identity: User identity in the form <lp|gh>:<username>
441
442 """
443 pass
444 import_ssh_keys = import_ssh_key
445
446 def get_machines(self, machine, utc=False):
447 """Return list of machines in this model.
448
449 :param str machine: Machine id, e.g. '0'
450 :param bool utc: Display time as UTC in RFC3339 format
451
452 """
453 pass
454
455 def get_shares(self):
456 """Return list of all users with access to this model.
457
458 """
459 pass
460
461 def get_spaces(self):
462 """Return list of all known spaces, including associated subnets.
463
464 """
465 pass
466
467 def get_ssh_key(self):
468 """Return known SSH keys for this model.
469
470 """
471 pass
472 get_ssh_keys = get_ssh_key
473
474 def get_storage(self, filesystem=False, volume=False):
475 """Return details of storage instances.
476
477 :param bool filesystem: Include filesystem storage
478 :param bool volume: Include volume storage
479
480 """
481 pass
482
483 def get_storage_pools(self, names=None, providers=None):
484 """Return list of storage pools.
485
486 :param list names: Only include pools with these names
487 :param list providers: Only include pools for these providers
488
489 """
490 pass
491
492 def get_subnets(self, space=None, zone=None):
493 """Return list of known subnets.
494
495 :param str space: Only include subnets in this space
496 :param str zone: Only include subnets in this zone
497
498 """
499 pass
500
501 def remove_blocks(self):
502 """Remove all blocks from this model.
503
504 """
505 pass
506
507 def remove_backup(self, backup_id):
508 """Delete a backup.
509
510 :param str backup_id: The id of the backup to remove
511
512 """
513 pass
514
515 def remove_cached_images(self, arch=None, kind=None, series=None):
516 """Remove cached OS images.
517
518 :param str arch: Architecture of the images to remove
519 :param str kind: Image kind to remove, e.g. 'lxd'
520 :param str series: Image series to remove, e.g. 'xenial'
521
522 """
523 pass
524
525 def remove_machine(self, *machine_ids):
526 """Remove a machine from this model.
527
528 :param str \*machine_ids: Ids of the machines to remove
529
530 """
531 pass
532 remove_machines = remove_machine
533
534 def remove_ssh_key(self, *keys):
535 """Remove a public SSH key(s) from this model.
536
537 :param str \*keys: Keys to remove
538
539 """
540 pass
541 remove_ssh_keys = remove_ssh_key
542
543 def restore_backup(
544 self, bootstrap=False, constraints=None, archive=None,
545 backup_id=None, upload_tools=False):
546 """Restore a backup archive to a new controller.
547
548 :param bool bootstrap: Bootstrap a new state machine
549 :param constraints: Model constraints
550 :type constraints: :class:`juju.Constraints`
551 :param str archive: Path to backup archive to restore
552 :param str backup_id: Id of backup to restore
553 :param bool upload_tools: Upload tools if bootstrapping a new machine
554
555 """
556 pass
557
558 def retry_provisioning(self):
559 """Retry provisioning for failed machines.
560
561 """
562 pass
563
564 def revoke(self, username, acl='read'):
565 """Revoke a user's access to this model.
566
567 :param str username: Username to revoke
568 :param str acl: Access control ('read' or 'write')
569
570 """
571 pass
572
573 def run(self, command, timeout=None):
574 """Run command on all machines in this model.
575
576 :param str command: The command to run
577 :param int timeout: Time to wait before command is considered failed
578
579 """
580 pass
581
582 def set_config(self, **config):
583 """Set configuration keys on this model.
584
585 :param \*\*config: Config key/values
586
587 """
588 pass
589
590 def set_constraints(self, constraints):
591 """Set machine constraints on this model.
592
593 :param :class:`juju.Constraints` constraints: Machine constraints
594
595 """
596 pass
597
598 def get_action_output(self, action_uuid, wait=-1):
599 """Get the results of an action by ID.
600
601 :param str action_uuid: Id of the action
602 :param int wait: Time in seconds to wait for action to complete
603
604 """
605 pass
606
607 def get_action_status(self, uuid_or_prefix=None, name=None):
608 """Get the status of all actions, filtered by ID, ID prefix, or action name.
609
610 :param str uuid_or_prefix: Filter by action uuid or prefix
611 :param str name: Filter by action name
612
613 """
614 pass
615
616 def get_budget(self, budget_name):
617 """Get budget usage info.
618
619 :param str budget_name: Name of budget
620
621 """
622 pass
623
624 def get_status(self, filter_=None, utc=False):
625 """Return the status of the model.
626
627 :param str filter_: Service or unit name or wildcard ('*')
628 :param bool utc: Display time as UTC in RFC3339 format
629
630 """
631 pass
632 status = get_status
633
634 def sync_tools(
635 self, all_=False, destination=None, dry_run=False, public=False,
636 source=None, stream=None, version=None):
637 """Copy Juju tools into this model.
638
639 :param bool all_: Copy all versions, not just the latest
640 :param str destination: Path to local destination directory
641 :param bool dry_run: Don't do the actual copy
642 :param bool public: Tools are for a public cloud, so generate mirrors
643 information
644 :param str source: Path to local source directory
645 :param str stream: Simplestreams stream for which to sync metadata
646 :param str version: Copy a specific major.minor version
647
648 """
649 pass
650
651 def unblock(self, *commands):
652 """Unblock an operation that would alter this model.
653
654 :param str \*commands: The commands to unblock. Valid values are
655 'all-changes', 'destroy-model', 'remove-object'
656
657 """
658 pass
659
660 def unset_config(self, *keys):
661 """Unset configuration on this model.
662
663 :param str \*keys: The keys to unset
664
665 """
666 pass
667
668 def upgrade_gui(self):
669 """Upgrade the Juju GUI for this model.
670
671 """
672 pass
673
674 def upgrade_juju(
675 self, dry_run=False, reset_previous_upgrade=False,
676 upload_tools=False, version=None):
677 """Upgrade Juju on all machines in a model.
678
679 :param bool dry_run: Don't do the actual upgrade
680 :param bool reset_previous_upgrade: Clear the previous (incomplete)
681 upgrade status
682 :param bool upload_tools: Upload local version of tools
683 :param str version: Upgrade to a specific version
684
685 """
686 pass
687
688 def upload_backup(self, archive_path):
689 """Store a backup archive remotely in Juju.
690
691 :param str archive_path: Path to local archive
692
693 """
694 pass