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