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