3 from dateutil
.parser
import parse
as parse_date
6 from .client
import client
8 log
= logging
.getLogger(__name__
)
11 class Unit(model
.ModelEntity
):
13 def agent_status(self
):
14 """Returns the current agent status string.
17 return self
.safe_data
['agent-status']['current']
20 def agent_status_since(self
):
21 """Get the time when the `agent_status` was last updated.
24 return parse_date(self
.safe_data
['agent-status']['since'])
27 def agent_status_message(self
):
28 """Get the agent status message.
31 return self
.safe_data
['agent-status']['message']
34 def workload_status(self
):
35 """Returns the current workload status string.
38 return self
.safe_data
['workload-status']['current']
41 def workload_status_since(self
):
42 """Get the time when the `workload_status` was last updated.
45 return parse_date(self
.safe_data
['workload-status']['since'])
48 def workload_status_message(self
):
49 """Get the workload status message.
52 return self
.safe_data
['workload-status']['message']
56 """Get the machine object for this unit.
59 machine_id
= self
.safe_data
['machine-id']
61 return self
.model
.machines
.get(machine_id
, None)
66 def public_address(self
):
67 """ Get the public address.
70 return self
.safe_data
['public-address'] or None
74 return 'unit-%s' % self
.name
.replace('/', '-')
76 def add_storage(self
, name
, constraints
=None):
77 """Add unit storage dynamically.
79 :param str name: Storage name, as specified by the charm
80 :param str constraints: Comma-separated list of constraints in the
81 form 'POOL,COUNT,SIZE'
84 raise NotImplementedError()
86 def collect_metrics(self
):
87 """Collect metrics on this unit.
90 raise NotImplementedError()
92 async def destroy(self
):
96 app_facade
= client
.ApplicationFacade
.from_connection(self
.connection
)
99 'Destroying %s', self
.name
)
101 return await app_facade
.DestroyUnits([self
.name
])
104 def get_resources(self
, details
=False):
105 """Return resources for this unit.
107 :param bool details: Include detailed info about resources used by each
111 raise NotImplementedError()
113 def resolved(self
, retry
=False):
114 """Mark unit errors resolved.
116 :param bool retry: Re-execute failed hooks
119 raise NotImplementedError()
121 async def run(self
, command
, timeout
=None):
122 """Run command on this unit.
124 :param str command: The command to run
125 :param int timeout: Time to wait before command is considered failed
126 :returns: A :class:`juju.action.Action` instance.
129 action
= client
.ActionFacade
.from_connection(self
.connection
)
132 'Running `%s` on %s', command
, self
.name
)
134 res
= await action
.Run(
141 return await self
.model
.wait_for_action(res
.results
[0].action
.tag
)
143 async def run_action(self
, action_name
, **params
):
144 """Run an action on this unit.
146 :param str action_name: Name of action to run
147 :param \*\*params: Action parameters
148 :returns: A :class:`juju.action.Action` instance.
150 Note that this only enqueues the action. You will need to call
151 ``action.wait()`` on the resulting `Action` instance if you wish
152 to block until the action is complete.
155 action_facade
= client
.ActionFacade
.from_connection(self
.connection
)
157 log
.debug('Starting action `%s` on %s', action_name
, self
.name
)
159 res
= await action_facade
.Enqueue([client
.Action(
164 action
= res
.results
[0].action
165 error
= res
.results
[0].error
166 if error
and error
.code
== 'not found':
167 raise ValueError('Action `%s` not found on %s' % (action_name
,
170 raise Exception('Unknown action error: %s' % error
.serialize())
171 action_id
= action
.tag
[len('action-'):]
172 log
.debug('Action started as %s', action_id
)
173 # we mustn't use wait_for_action because that blocks until the
174 # action is complete, rather than just being in the model
175 return await self
.model
._wait
_for
_new
('action', action_id
)
177 async def scp_to(self
, source
, destination
, user
='ubuntu', proxy
=False,
179 """Transfer files to this unit.
181 :param str source: Local path of file(s) to transfer
182 :param str destination: Remote destination of transferred files
183 :param str user: Remote username
184 :param bool proxy: Proxy through the Juju API server
185 :param str scp_opts: Additional options to the `scp` command
187 await self
.machine
.scp_to(source
, destination
, user
=user
, proxy
=proxy
,
190 async def scp_from(self
, source
, destination
, user
='ubuntu', proxy
=False,
192 """Transfer files from this unit.
194 :param str source: Remote path of file(s) to transfer
195 :param str destination: Local destination of transferred files
196 :param str user: Remote username
197 :param bool proxy: Proxy through the Juju API server
198 :param str scp_opts: Additional options to the `scp` command
200 await self
.machine
.scp_from(source
, destination
, user
=user
,
201 proxy
=proxy
, scp_opts
=scp_opts
)
203 def set_meter_status(self
):
204 """Set the meter status on this unit.
207 raise NotImplementedError()
210 self
, command
, user
=None, proxy
=False, ssh_opts
=None):
211 """Execute a command over SSH on this unit.
213 :param str command: Command to execute
214 :param str user: Remote username
215 :param bool proxy: Proxy through the Juju API server
216 :param str ssh_opts: Additional options to the `ssh` command
219 raise NotImplementedError()
221 def status_history(self
, num
=20, utc
=False):
222 """Get status history for this unit.
224 :param int num: Size of history backlog
225 :param bool utc: Display time as UTC in RFC3339 format
228 raise NotImplementedError()
230 async def is_leader_from_status(self
):
232 Check to see if this unit is the leader. Returns True if so, and
233 False if it is not, or if leadership does not make sense
234 (e.g., there is no leader in this application.)
236 This method is a kluge that calls FullStatus in the
237 ClientFacade to get its information. Once
238 https://bugs.launchpad.net/juju/+bug/1643691 is resolved, we
239 should add a simple .is_leader property, and deprecate this
243 app
= self
.name
.split("/")[0]
245 c
= client
.ClientFacade
.from_connection(self
.connection
)
247 status
= await c
.FullStatus(None)
249 # FullStatus may be more up to date than our model, and the
250 # unit may have gone away, or we may be doing something silly,
251 # like trying to fetch leadership for a subordinate, which
252 # will not be filed where we expect in the model. In those
253 # cases, we may simply return False, as a nonexistent or
254 # subordinate unit is not a leader.
255 if not status
.applications
.get(app
):
258 if not status
.applications
[app
].get('units'):
261 if not status
.applications
[app
]['units'].get(self
.name
):
264 return status
.applications
[app
]['units'][self
.name
].get('leader',
267 async def get_metrics(self
):
268 """Get metrics for the unit.
270 :return: Dictionary of metrics for this unit.
273 metrics
= await self
.model
.get_metrics(self
.tag
)
274 return metrics
[self
.name
]