8719a629d2153b63374a3959b70f29c89d825793
[osm/N2VC.git] / juju / application.py
1 import asyncio
2 import logging
3
4 from . import model
5 from .client import client
6 from .errors import JujuError
7 from .placement import parse as parse_placement
8
9 log = logging.getLogger(__name__)
10
11
12 class Application(model.ModelEntity):
13 @property
14 def _unit_match_pattern(self):
15 return r'^{}.*$'.format(self.entity_id)
16
17 def on_unit_add(self, callable_):
18 """Add a "unit added" observer to this entity, which will be called
19 whenever a unit is added to this application.
20
21 """
22 self.model.add_observer(
23 callable_, 'unit', 'add', self._unit_match_pattern)
24
25 def on_unit_remove(self, callable_):
26 """Add a "unit removed" observer to this entity, which will be called
27 whenever a unit is removed from this application.
28
29 """
30 self.model.add_observer(
31 callable_, 'unit', 'remove', self._unit_match_pattern)
32
33 @property
34 def units(self):
35 return [
36 unit for unit in self.model.units.values()
37 if unit.application == self.name
38 ]
39
40 @property
41 def status(self):
42 """Get the application status, as set by the charm's leader.
43
44 """
45 return self.safe_data['status']['current']
46
47 @property
48 def status_message(self):
49 """Get the application status message, as set by the charm's leader.
50
51 """
52 return self.safe_data['status']['message']
53
54 @property
55 def tag(self):
56 return 'application-%s' % self.name
57
58 async def add_relation(self, local_relation, remote_relation):
59 """Add a relation to another application.
60
61 :param str local_relation: Name of relation on this application
62 :param str remote_relation: Name of relation on the other
63 application in the form '<application>[:<relation_name>]'
64
65 """
66 if ':' not in local_relation:
67 local_relation = '{}:{}'.format(self.name, local_relation)
68
69 return await self.model.add_relation(local_relation, remote_relation)
70
71 async def add_unit(self, count=1, to=None):
72 """Add one or more units to this application.
73
74 :param int count: Number of units to add
75 :param str to: Placement directive, e.g.::
76 '23' - machine 23
77 'lxc:7' - new lxc container on machine 7
78 '24/lxc/3' - lxc container 3 or machine 24
79
80 If None, a new machine is provisioned.
81
82 """
83 app_facade = client.ApplicationFacade.from_connection(self.connection)
84
85 log.debug(
86 'Adding %s unit%s to %s',
87 count, '' if count == 1 else 's', self.name)
88
89 result = await app_facade.AddUnits(
90 application=self.name,
91 placement=parse_placement(to) if to else None,
92 num_units=count,
93 )
94
95 return await asyncio.gather(*[
96 asyncio.ensure_future(self.model._wait_for_new('unit', unit_id))
97 for unit_id in result.units
98 ])
99
100 add_units = add_unit
101
102 def allocate(self, budget, value):
103 """Allocate budget to this application.
104
105 :param str budget: Name of budget
106 :param int value: Budget limit
107
108 """
109 raise NotImplementedError()
110
111 def attach(self, resource_name, file_path):
112 """Upload a file as a resource for this application.
113
114 :param str resource: Name of the resource
115 :param str file_path: Path to the file to upload
116
117 """
118 raise NotImplementedError()
119
120 def collect_metrics(self):
121 """Collect metrics on this application.
122
123 """
124 raise NotImplementedError()
125
126 async def destroy_relation(self, local_relation, remote_relation):
127 """Remove a relation to another application.
128
129 :param str local_relation: Name of relation on this application
130 :param str remote_relation: Name of relation on the other
131 application in the form '<application>[:<relation_name>]'
132
133 """
134 if ':' not in local_relation:
135 local_relation = '{}:{}'.format(self.name, local_relation)
136
137 app_facade = client.ApplicationFacade.from_connection(self.connection)
138
139 log.debug(
140 'Destroying relation %s <-> %s', local_relation, remote_relation)
141
142 return await app_facade.DestroyRelation([
143 local_relation, remote_relation])
144 remove_relation = destroy_relation
145
146 async def destroy_unit(self, *unit_names):
147 """Destroy units by name.
148
149 """
150 return await self.model.destroy_units(*unit_names)
151 destroy_units = destroy_unit
152
153 async def destroy(self):
154 """Remove this application from the model.
155
156 """
157 app_facade = client.ApplicationFacade.from_connection(self.connection)
158
159 log.debug(
160 'Destroying %s', self.name)
161
162 return await app_facade.Destroy(self.name)
163 remove = destroy
164
165 async def expose(self):
166 """Make this application publicly available over the network.
167
168 """
169 app_facade = client.ApplicationFacade.from_connection(self.connection)
170
171 log.debug(
172 'Exposing %s', self.name)
173
174 return await app_facade.Expose(self.name)
175
176 async def get_config(self):
177 """Return the configuration settings dict for this application.
178
179 """
180 app_facade = client.ApplicationFacade.from_connection(self.connection)
181
182 log.debug(
183 'Getting config for %s', self.name)
184
185 return (await app_facade.Get(self.name)).config
186
187 async def get_constraints(self):
188 """Return the machine constraints dict for this application.
189
190 """
191 app_facade = client.ApplicationFacade.from_connection(self.connection)
192
193 log.debug(
194 'Getting constraints for %s', self.name)
195
196 result = (await app_facade.Get(self.name)).constraints
197 return vars(result) if result else result
198
199 def get_actions(self, schema=False):
200 """Get actions defined for this application.
201
202 :param bool schema: Return the full action schema
203
204 """
205 raise NotImplementedError()
206
207 def get_resources(self, details=False):
208 """Return resources for this application.
209
210 :param bool details: Include detailed info about resources used by each
211 unit
212
213 """
214 raise NotImplementedError()
215
216 async def run(self, command, timeout=None):
217 """Run command on all units for this application.
218
219 :param str command: The command to run
220 :param int timeout: Time to wait before command is considered failed
221
222 """
223 action = client.ActionFacade.from_connection(self.connection)
224
225 log.debug(
226 'Running `%s` on all units of %s', command, self.name)
227
228 # TODO this should return a list of Actions
229 return await action.Run(
230 [self.name],
231 command,
232 [],
233 timeout,
234 [],
235 )
236
237 async def set_annotations(self, annotations):
238 """Set annotations on this application.
239
240 :param annotations map[string]string: the annotations as key/value
241 pairs.
242
243 """
244 log.debug('Updating annotations on application %s', self.name)
245
246 self.ann_facade = client.AnnotationsFacade.from_connection(
247 self.connection)
248
249 ann = client.EntityAnnotations(
250 entity=self.tag,
251 annotations=annotations,
252 )
253 return await self.ann_facade.Set([ann])
254
255 async def set_config(self, config, to_default=False):
256 """Set configuration options for this application.
257
258 :param config: Dict of configuration to set
259 :param bool to_default: Set application options to default values
260
261 """
262 app_facade = client.ApplicationFacade.from_connection(self.connection)
263
264 log.debug(
265 'Setting config for %s: %s', self.name, config)
266
267 return await app_facade.Set(self.name, config)
268
269 async def set_constraints(self, constraints):
270 """Set machine constraints for this application.
271
272 :param dict constraints: Dict of machine constraints
273
274 """
275 app_facade = client.ApplicationFacade.from_connection(self.connection)
276
277 log.debug(
278 'Setting constraints for %s: %s', self.name, constraints)
279
280 return await app_facade.SetConstraints(self.name, constraints)
281
282 def set_meter_status(self, status, info=None):
283 """Set the meter status on this status.
284
285 :param str status: Meter status, e.g. 'RED', 'AMBER'
286 :param str info: Extra info message
287
288 """
289 raise NotImplementedError()
290
291 def set_plan(self, plan_name):
292 """Set the plan for this application, effective immediately.
293
294 :param str plan_name: Name of plan
295
296 """
297 raise NotImplementedError()
298
299 async def unexpose(self):
300 """Remove public availability over the network for this application.
301
302 """
303 app_facade = client.ApplicationFacade.from_connection(self.connection)
304
305 log.debug(
306 'Unexposing %s', self.name)
307
308 return await app_facade.Unexpose(self.name)
309
310 def update_allocation(self, allocation):
311 """Update existing allocation for this application.
312
313 :param int allocation: The allocation to set
314
315 """
316 raise NotImplementedError()
317
318 async def upgrade_charm(
319 self, channel=None, force_series=False, force_units=False,
320 path=None, resources=None, revision=None, switch=None):
321 """Upgrade the charm for this application.
322
323 :param str channel: Channel to use when getting the charm from the
324 charm store, e.g. 'development'
325 :param bool force_series: Upgrade even if series of deployed
326 application is not supported by the new charm
327 :param bool force_units: Upgrade all units immediately, even if in
328 error state
329 :param str path: Uprade to a charm located at path
330 :param dict resources: Dictionary of resource name/filepath pairs
331 :param int revision: Explicit upgrade revision
332 :param str switch: Crossgrade charm url
333
334 """
335 # TODO: Support local upgrades
336 if path is not None:
337 raise NotImplementedError("path option is not implemented")
338 if resources is not None:
339 raise NotImplementedError("resources option is not implemented")
340
341 if switch is not None and revision is not None:
342 raise ValueError("switch and revision are mutually exclusive")
343
344 client_facade = client.ClientFacade.from_connection(self.connection)
345 app_facade = client.ApplicationFacade.from_connection(self.connection)
346
347 if switch is not None:
348 charm_url = switch
349 if not charm_url.startswith('cs:'):
350 charm_url = 'cs:' + charm_url
351 else:
352 charm_url = self.data['charm-url']
353 charm_url = charm_url.rpartition('-')[0]
354 if revision is not None:
355 charm_url = "%s-%d" % (charm_url, revision)
356 else:
357 charmstore = self.model.charmstore
358 entity = await charmstore.entity(charm_url, channel=channel)
359 charm_url = entity['Id']
360
361 if charm_url == self.data['charm-url']:
362 raise JujuError('already running charm "%s"' % charm_url)
363
364 await client_facade.AddCharm(
365 url=charm_url,
366 channel=channel
367 )
368
369 await app_facade.SetCharm(
370 application=self.entity_id,
371 channel=channel,
372 charm_url=charm_url,
373 config_settings=None,
374 config_settings_yaml=None,
375 force_series=force_series,
376 force_units=force_units,
377 resource_ids=None,
378 storage_constraints=None
379 )
380
381 await self.model.block_until(
382 lambda: self.data['charm-url'] == charm_url
383 )
384
385 async def get_metrics(self):
386 """Get metrics for this application's units.
387
388 :return: Dictionary of unit_name:metrics
389
390 """
391 return await self.model.get_metrics(self.tag)