ea51345c19292ac5fb26f0a74c96e30149a9955d
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 return 'unit-%s' % self
.name
.replace('/', '-')
58 def add_storage(self
, name
, constraints
=None):
59 """Add unit storage dynamically.
61 :param str name: Storage name, as specified by the charm
62 :param str constraints: Comma-separated list of constraints in the
63 form 'POOL,COUNT,SIZE'
68 def collect_metrics(self
):
69 """Collect metrics on this unit.
74 async def destroy(self
):
78 app_facade
= client
.ApplicationFacade()
79 app_facade
.connect(self
.connection
)
82 'Destroying %s', self
.name
)
84 return await app_facade
.DestroyUnits([self
.name
])
87 def get_resources(self
, details
=False):
88 """Return resources for this unit.
90 :param bool details: Include detailed info about resources used by each
96 def resolved(self
, retry
=False):
97 """Mark unit errors resolved.
99 :param bool retry: Re-execute failed hooks
104 async def run(self
, command
, timeout
=None):
105 """Run command on this unit.
107 :param str command: The command to run
108 :param int timeout: Time to wait before command is considered failed
109 :returns: A :class:`juju.action.Action` instance.
111 Returns a tuple containing the stdout, stderr, and return code
115 action
= client
.ActionFacade()
116 action
.connect(self
.connection
)
119 'Running `%s` on %s', command
, self
.name
)
121 res
= await action
.Run(
128 return await self
.model
.wait_for_action(res
.results
[0].action
.tag
)
130 async def run_action(self
, action_name
, **params
):
131 """Run an action on this unit.
133 :param str action_name: Name of action to run
134 :param \*\*params: Action parameters
135 :returns: A :class:`juju.action.Action` instance.
137 Note that this only enqueues the action. You will need to call
138 ``action.wait()`` on the resulting `Action` instance if you wish
139 to block until the action is complete.
142 action_facade
= client
.ActionFacade()
143 action_facade
.connect(self
.connection
)
145 log
.debug('Starting action `%s` on %s', action_name
, self
.name
)
147 res
= await action_facade
.Enqueue([client
.Action(
152 action
= res
.results
[0].action
153 error
= res
.results
[0].error
154 if error
and error
.code
== 'not found':
155 raise ValueError('Action `%s` not found on %s' % (action_name
,
158 raise Exception('Unknown action error: %s' % error
.serialize())
159 action_id
= action
.tag
[len('action-'):]
160 log
.debug('Action started as %s', action_id
)
161 # we mustn't use wait_for_action because that blocks until the
162 # action is complete, rather than just being in the model
163 return await self
.model
._wait
_for
_new
('action', action_id
)
166 self
, source_path
, user
=None, destination_path
=None, proxy
=False,
168 """Transfer files to this unit.
170 :param str source_path: Path of file(s) to transfer
171 :param str user: Remote username
172 :param str destination_path: Destination of transferred files on
174 :param bool proxy: Proxy through the Juju API server
175 :param str scp_opts: Additional options to the `scp` command
180 def set_meter_status(self
):
181 """Set the meter status on this unit.
187 self
, command
, user
=None, proxy
=False, ssh_opts
=None):
188 """Execute a command over SSH on this unit.
190 :param str command: Command to execute
191 :param str user: Remote username
192 :param bool proxy: Proxy through the Juju API server
193 :param str ssh_opts: Additional options to the `ssh` command
198 def status_history(self
, num
=20, utc
=False):
199 """Get status history for this unit.
201 :param int num: Size of history backlog
202 :param bool utc: Display time as UTC in RFC3339 format
207 async def is_leader_from_status(self
):
209 Check to see if this unit is the leader. Returns True if so, and
210 False if it is not, or if leadership does not make sense
211 (e.g., there is no leader in this application.)
213 This method is a kluge that calls FullStatus in the
214 ClientFacade to get its information. Once
215 https://bugs.launchpad.net/juju/+bug/1643691 is resolved, we
216 should add a simple .is_leader property, and deprecate this
220 app
= self
.name
.split("/")[0]
222 c
= client
.ClientFacade()
223 c
.connect(self
.model
.connection
)
225 status
= await c
.FullStatus(None)
227 # FullStatus may be more up to date than our model, and the
228 # unit may have gone away, or we may be doing something silly,
229 # like trying to fetch leadership for a subordinate, which
230 # will not be filed where we expect in the model. In those
231 # cases, we may simply return False, as a nonexistent or
232 # subordinate unit is not a leader.
233 if not status
.applications
.get(app
):
236 if not status
.applications
[app
].get('units'):
239 if not status
.applications
[app
]['units'].get(self
.name
):
242 return status
.applications
[app
]['units'][self
.name
].get('leader',
245 async def get_metrics(self
):
246 metrics
= await self
.model
.get_metrics(self
.tag
)
247 return metrics
[self
.name
]