/
model.py
3281 lines (2691 loc) · 115 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for interacting with a juju model.
This module contains a number of functions for interacting with a Juju model
mostly via libjuju. Async function also provice a non-async alternative via
'sync_wrapper'.
"""
import asyncio
from async_generator import async_generator, yield_, asynccontextmanager
import collections
import datetime
import inspect
import logging
import os
import re
import subprocess
import tempfile
import yaml
from oslo_config import cfg
import concurrent
import time
import juju.client
from juju.errors import JujuError
from juju.model import Model
from zaza import sync_wrapper
import zaza.utilities.generic as generic_utils
import zaza.utilities.exceptions as zaza_exceptions
from zaza.utilities import deprecate
# Default for the Juju MAX_FRAME_SIZE to be 256MB to stop
# "RPC: Connection closed, reconnecting" errors and then a failure in the log.
# See https://github.com/juju/python-libjuju/issues/458 for more details
JUJU_MAX_FRAME_SIZE = 2**30
APPS_LEFT_INTERVAL = 600
CURRENT_MODEL = None
MODEL_ALIASES = {}
class ModelTimeout(Exception):
"""Model timeout exception."""
pass
class RemoteFileError(Exception):
"""Error with a remote file."""
pass
def set_juju_model(model_name):
"""Point environment at the given model.
:param model_name: Model to point environment at
:type model_name: str
"""
global CURRENT_MODEL
os.environ["JUJU_MODEL"] = model_name
CURRENT_MODEL = model_name
def set_juju_model_aliases(model_aliases):
"""Store the model aliases in a global.
:param model_aliases: Model alias map to store
:type model_aliases: dict
"""
global MODEL_ALIASES
MODEL_ALIASES = model_aliases
def get_juju_model_aliases():
"""Return the model aliases from global.
:returns: Model alias map
:rtype: dict
"""
global MODEL_ALIASES
return MODEL_ALIASES
def unset_juju_model_aliases():
"""Remove model alias data."""
set_juju_model_aliases({})
async def async_get_juju_model():
"""Retrieve current model.
First check the environment for JUJU_MODEL. If this is not set, get the
current active model.
:returns: In focus model name
:rtype: str
"""
global CURRENT_MODEL
if CURRENT_MODEL:
return CURRENT_MODEL
# LY: I think we should remove the KeyError handling. I don't think we
# should ever fall back to the model in focus because it will lead
# to functions being added which do not explicitly set a model and
# zaza will loose the ability to do concurrent runs.
try:
# Check the environment
CURRENT_MODEL = os.environ["JUJU_MODEL"]
except KeyError:
try:
CURRENT_MODEL = os.environ["MODEL_NAME"]
except KeyError:
# If unset connect get the current active model
CURRENT_MODEL = await async_get_current_model()
return CURRENT_MODEL
get_juju_model = sync_wrapper(async_get_juju_model)
async def deployed(model_name=None):
"""List deployed applications.
:param model_name: Name of the model to list applications from
:type model_name: string
"""
# Create a Model instance. We need to connect our Model to a Juju api
# server before we can use it.
# NOTE(tinwood): Due to https://github.com/juju/python-libjuju/issues/458
# set the max frame size to something big to stop
# "RPC: Connection closed, reconnecting" messages and then failures.
model = Model(max_frame_size=JUJU_MAX_FRAME_SIZE)
if not model_name:
# Connect to the currently active Juju model
await model.connect_current()
else:
await model.connect_model(model_name)
try:
# list currently deployed services
return list(model.applications.keys())
finally:
# Disconnect from the api server and cleanup.
await model.disconnect()
sync_deployed = sync_wrapper(deployed)
async def async_get_unit_from_name(unit_name, model=None, model_name=None):
"""Return the units that corresponds to the name in the given model.
:param unit_name: Name of unit to match
:type unit_name: str
:param model: Model to perform lookup in
:type model: model.Model()
:param model_name: Name of the model to perform lookup in
:type model_name: string
:returns: Unit matching given name
:rtype: juju.unit.Unit or None
:raises: UnitNotFound
"""
app = unit_name.split('/')[0]
unit = None
try:
if model is None:
model = await get_model(model_name)
units = model.applications[app].units
except KeyError:
msg = ('Application: {} does not exist in current model'.
format(app))
logging.error(msg)
raise UnitNotFound(unit_name)
for u in units:
if u.entity_id == unit_name:
unit = u
break
else:
raise UnitNotFound(unit_name)
return unit
get_unit_from_name = sync_wrapper(async_get_unit_from_name)
# A collection of model name -> libjuju models associations; use to either
# instantiate or handout a model, or start a new one.
ModelRefs = {}
async def get_model_memo(model_name):
"""Get the libjuju Model object for a name.
This is memoed as the model is maintained as running in a separate
background thread. Thus, essentially this is a singleton for each of
the model names.
:param model_name: the model name to get a Model for.
:type model_name: str
:returns: juju.model.Model
"""
global ModelRefs
model = None
if model_name in ModelRefs:
model = ModelRefs[model_name]
if is_model_disconnected(model):
try:
await model.disconnect()
except Exception:
pass
model = None
del ModelRefs[model_name]
if model is None:
# NOTE(tinwood): Due to
# https://github.com/juju/python-libjuju/issues/458 set the max frame
# size to something big to stop "RPC: Connection closed, reconnecting"
# messages and then failures.
model = Model(max_frame_size=JUJU_MAX_FRAME_SIZE)
await model.connect(model_name)
ModelRefs[model_name] = model
return model
async def get_model(model_name=None):
"""Get (or create) the current model for `model_name`.
If None is passed, or there is no model_name param, then the current model
is fetched.
:param model_name: the juju.model.Model object to fetch
:type model_name: Optional[str]
:returns: juju.model.Model
"""
if not model_name:
model_name = await async_get_juju_model()
return await get_model_memo(model_name)
async def remove_model_memo(model_name):
"""Remove/disconnect a model singleton object.
The Model runs in an async background thread. This removes it by
name and disconnects it if it is running.
:param model_name: the model name to remove a Model object.
:type model_name: str
"""
global ModelRefs
try:
model = ModelRefs[model_name]
del ModelRefs[model_name]
await model.disconnect()
except Exception:
pass
async def remove_models_memo():
"""Remove all the models that are memoed."""
model_names = list(ModelRefs.keys())
for model_name in model_names:
await remove_model_memo(model_name)
@asynccontextmanager
@async_generator
@deprecate()
async def run_in_model(model_name):
"""DEPRECATED: Context manager for executing code inside a libjuju model.
Example of using run_in_model:
async with run_in_model(model_name) as model:
model.do_something()
NOTE(ajkavanagh) this function is deprecated. Don't use a contextmanager
and instead just use:
model = await get_model(model_name)
Note: that this function re-uses an existing Model connection as zaza (now)
tries to keep the model connected for the entire run that it is needed.
This is so that libjuju objects connected to the model continue to be
updated and that associated methods on those objects continue to function.
Use zaza.model.connect_model(model_name) and
zaza.model.disconnect_mode(model_name) to control the lifetime of
connecting to a model.
:param model_name: Name of model to run function in
:type model_name: str
:returns: The juju Model object correcsponding to model_name
:rtype: Iterator[:class:'juju.Model()']
"""
model = await get_model(model_name)
# This doesn't need to be a generator as we now keep models alive until
# they are disconnected. This is purely kept (in this deprecated function)
# to maintain the API until run_in_model() is removed.
await yield_(model)
def is_model_disconnected(model):
"""Return True if the model is disconnected.
:param model: the model to check
:type model: :class:'juju.Model'
:returns: True if disconnected
:rtype: bool
"""
return not (model.is_connected() and model.connection().is_open)
async def ensure_model_connected(model):
"""Ensure that the model is connected.
If model is disconnected then reconnect it.
:param model: the model to check
:type model: :class:'juju.Model'
"""
if is_model_disconnected(model):
model_name = model.info.name
logging.warning(
"model: %s has disconnected, forcing full disconnection "
"and then reconnecting ...", model_name)
try:
await model.disconnect()
except Exception:
# We don't care if disconnect fails; we're much more
# interested in re-connecting, and this is just to clean up
# anything that might be left over (i.e.
# model.is_connected() might be true, but
# model.connection().is_open may be false
pass
logging.warning("Attempting to reconnect model %s", model_name)
await model.connect_model(model_name)
async def block_until_auto_reconnect_model(*conditions,
model=None,
aconditions=None,
timeout=None,
wait_period=0.5):
"""Async block on the model until conditions met.
This function doesn't use model.block_until() which unfortunately raises
websockets.exceptions.ConnectionClosed if the connections gets closed,
which seems to happen quite frequently. This funtion blocks until the
conditions are met or a timeout occurs, and reconnects the model if it
becomes disconnected.
Note that conditions are just passed as an unamed list in the function call
to make it work more like the more simple 'block_until' function.
Note: conditions must capture libjuju objects in closures as the model may
change if it is disconnected. The closures should refetch the juju objects
from the model as needed.
:param model: the model to use
:type model: :class:'juju.Model()'
:param conditions: a list of callables that need to evaluate to True.
:type conditions: [List[Callable[[:class:'juju.Model()'], bool]]]
:param aconditions: an optional list of async callables that need to
evaluate to True.
:type aconditions:
Optional[List[AsyncCallable[[:class:'juju.Model()'], bool]]]
:param timeout: the timeout to wait for the block on.
:type timeout: float
:param wait_period: The time to sleep between checking the conditions.
:type wait_period: float
:raises: TimeoutError if the conditions never match (assuming timeout is
not None).
"""
assert model is not None, ("model can't be None in "
"block_until_auto_reconnect_model()")
aconditions = aconditions or []
def _done():
return all(c() for c in conditions)
async def _adone():
evaluated = []
# note Python 3.5 doesn't support async comprehensions; do it the old
# fashioned way.
for c in aconditions:
evaluated.append(await c())
if is_model_disconnected(model):
return False
return all(evaluated)
async def _block():
while True:
# reconnect if disconnected, as the conditions still need to be
# checked.
await ensure_model_connected(model)
result = _done()
aresult = await _adone()
if all((not is_model_disconnected(model), result, aresult)):
return
else:
await asyncio.sleep(wait_period)
# finally wait for all the conditions to be true
await asyncio.wait_for(_block(), timeout)
async def async_get_model_info(model_name=None):
"""Get information about the model.
Useful keys in the ModelInfo object include:
'agent-version', 'cloud-region', 'name', 'owner-tag', 'provider-type',
'type'
:param model_name: Name of model to gather information on.
:type model_name: str
:returns: The Model info object
:rtype: juju.client._definitions.ModelInfo
"""
model = await get_model(model_name)
return model.info
get_model_info = sync_wrapper(async_get_model_info)
async def async_scp_to_unit(unit_name, source, destination, model_name=None,
user='ubuntu', proxy=False, scp_opts=''):
"""Transfer files to unit_name in model_name.
:param model_name: Name of model unit is in
:type model_name: str
:param unit_name: Name of unit to scp to
:type unit_name: str
:param source: Local path of file(s) to transfer
:type source: str
:param destination: Remote destination of transferred files
:type source: str
:param user: Remote username
:type source: str
:param proxy: Proxy through the Juju API server
:type proxy: bool
:param scp_opts: Additional options to the scp command
:type scp_opts: str
"""
model = await get_model(model_name)
unit = await async_get_unit_from_name(unit_name, model)
await unit.scp_to(source, destination, user=user, proxy=proxy,
scp_opts=scp_opts)
scp_to_unit = sync_wrapper(async_scp_to_unit)
async def async_scp_to_all_units(application_name, source, destination,
model_name=None, user='ubuntu', proxy=False,
scp_opts=''):
"""Transfer files to all units of an application.
:param model_name: Name of model unit is in
:type model_name: str
:param application_name: Name of application to scp file to
:type application_name: str
:param source: Local path of file(s) to transfer
:type source: str
:param destination: Remote destination of transferred files
:type source: str
:param user: Remote username
:type source: str
:param proxy: Proxy through the Juju API server
:type proxy: bool
:param scp_opts: Additional options to the scp command
:type scp_opts: str
"""
model = await get_model(model_name)
for unit in model.applications[application_name].units:
# FIXME: Should scp in parallel
await unit.scp_to(source, destination, user=user, proxy=proxy,
scp_opts=scp_opts)
scp_to_all_units = sync_wrapper(async_scp_to_all_units)
async def async_scp_from_unit(unit_name, source, destination, model_name=None,
user='ubuntu', proxy=False, scp_opts=''):
"""Transfer files from unit_name in model_name.
:param model_name: Name of model unit is in
:type model_name: str
:param unit_name: Name of unit to scp from
:type unit_name: str
:param source: Remote path of file(s) to transfer
:type source: str
:param destination: Local destination of transferred files
:type source: str
:param user: Remote username
:type source: str
:param proxy: Proxy through the Juju API server
:type proxy: bool
:param scp_opts: Additional options to the scp command
:type scp_opts: str
"""
model = await get_model(model_name)
unit = await async_get_unit_from_name(unit_name, model)
await unit.scp_from(source, destination, user=user, proxy=proxy,
scp_opts=scp_opts)
scp_from_unit = sync_wrapper(async_scp_from_unit)
def _normalise_action_results(results):
"""Put action results in a consistent format.
:param results: Results dictionary to process.
:type results: Dict[str, str]
:returns: {
'Code': '',
'Stderr': '',
'Stdout': '',
'stderr': '',
'stdout': ''}
:rtype: Dict[str, str]
"""
if results:
# In Juju 2.7 some keys are dropped from the results if their
# value was empty. This breaks some functions downstream, so
# ensure the keys are always present.
for key in ['Stderr', 'Stdout', 'stderr', 'stdout']:
results[key] = results.get(key, '')
# Juju has started using a lowercase "stdout" key in new action
# commands in recent versions. Ensure the old capatalised keys and
# the new lowercase keys are present and point to the same value to
# avoid breaking functions downstream.
for key in ['stderr', 'stdout']:
old_key = key.capitalize()
if results.get(key) and not results.get(old_key):
results[old_key] = results[key]
elif results.get(old_key) and not results.get(key):
results[key] = results[old_key]
if 'return-code' in results:
results['Code'] = str(results.get('return-code'))
del results['return-code']
return results
else:
return {}
async def async_run_on_unit(unit_name, command, model_name=None, timeout=None):
"""Juju run on unit.
:param model_name: Name of model unit is in
:type model_name: str
:param unit_name: Name of unit to match
:type unit: str
:param command: Command to execute
:type command: str
:param timeout: How long in seconds to wait for command to complete
:type timeout: int
:returns: action.data['results'] {'Code': '', 'Stderr': '', 'Stdout': ''}
:rtype: dict
"""
model = await get_model(model_name)
unit = await async_get_unit_from_name(unit_name, model)
action = await generic_utils.unit_run(unit, command, timeout)
action = _normalise_action_object(action)
results = action.data.get('results')
return _normalise_action_results(results)
run_on_unit = sync_wrapper(async_run_on_unit)
async def async_run_on_leader(application_name, command, model_name=None,
timeout=None):
"""Juju run on leader unit.
:param application_name: Application to match
:type application_name: str
:param command: Command to execute
:type command: str
:param model_name: Name of model unit is in
:type model_name: str
:param timeout: How long in seconds to wait for command to complete
:type timeout: int
:returns: action.data['results'] {'Code': '', 'Stderr': '', 'Stdout': ''}
:rtype: dict
"""
model = await get_model(model_name)
for unit in model.applications[application_name].units:
is_leader = await unit.is_leader_from_status()
if is_leader:
action = await generic_utils.unit_run(unit, command, timeout)
action = _normalise_action_object(action)
results = action.data.get('results')
return _normalise_action_results(results)
run_on_leader = sync_wrapper(async_run_on_leader)
async def async_get_unit_time(unit_name, model_name=None, timeout=None):
"""Get the current time (in seconds since Epoch) on the given unit.
:param model_name: Name of model to query.
:type model_name: str
:param unit_name: Name of unit to run action on
:type unit_name: str
:returns: time in seconds since Epoch on unit
:rtype: int
"""
out = await async_run_on_unit(
unit_name=unit_name,
command="date +'%s'",
model_name=model_name,
timeout=timeout)
return int(out['Stdout'])
get_unit_time = sync_wrapper(async_get_unit_time)
async def async_get_systemd_service_active_time(unit_name, service,
model_name=None, timeout=None):
r"""Return the time that the given service was last active.
Note: The service does not have to be currently running, the time returned
relates to the last time the systemd service entered an 'active'
state.
:param unit_name: Name of unit to run action on
:type unit_name: str
:param service: Name of service to check active time
:type service: str
:param model_name: Name of model to query.
:type model_name: str
:param timeout: Time to wait for status to be achieved
:type timeout: int
"""
cmd = "systemctl show {} --property=ActiveEnterTimestamp".format(service)
out = await async_run_on_unit(
unit_name=unit_name,
command=cmd,
model_name=model_name,
timeout=timeout)
str_time = out['Stdout'].rstrip().replace('ActiveEnterTimestamp=', '')
start_time = datetime.datetime.strptime(
str_time,
'%a %Y-%m-%d %H:%M:%S %Z')
return start_time
get_systemd_service_active_time = sync_wrapper(
async_get_systemd_service_active_time)
async def async_get_unit_service_start_time(unit_name, service,
model_name=None, timeout=None,
pgrep_full=False):
r"""Return the time that the given service was started on a unit.
Return the time (in seconds since Epoch) that the oldest process of the
given service was started on the given unit. If the service is not running
raise ServiceNotRunning exception.
If pgrep_full is True ensure that any special characters in the name of
the service are escaped e.g.
service = 'aodh-evaluator: AlarmEvaluationService worker\(0\)'
:param model_name: Name of model to query.
:type model_name: str
:param unit_name: Name of unit to run action on
:type unit_name: str
:param service: Name of service to check is running
:type service: str
:param timeout: Time to wait for status to be achieved
:type timeout: int
:param pgrep_full: Should pgrep be used rather than pidof to identify
a service.
:type pgrep_full: bool
:returns: time in seconds since Epoch on unit
:rtype: int
:raises: ServiceNotRunning
"""
if pgrep_full:
pid_cmd = r"pgrep -o -f '{}'".format(service)
cmd = "stat -c %Y /proc/$({})".format(pid_cmd)
else:
pid_cmd = r"pidof -x '{}'".format(service)
cmd = pid_cmd + (
"| "
r"tr -d '\n' | "
"xargs -d' ' -I {} stat -c %Y /proc/{} | "
"sort -n |"
" head -1")
out = await async_run_on_unit(
unit_name=unit_name,
command=cmd,
model_name=model_name,
timeout=timeout)
out = out['Stdout'].strip()
if out:
return int(out)
else:
raise ServiceNotRunning(service)
get_unit_service_start_time = sync_wrapper(async_get_unit_service_start_time)
async def async_get_application(application_name, model_name=None):
"""Return an application object.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application to retrieve units for
:type application_name: str
:returns: Application object
:rtype: object
"""
model = await get_model(model_name)
return model.applications[application_name]
get_application = sync_wrapper(async_get_application)
async def async_get_units(application_name, model_name=None):
"""Return all the units of a given application.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application to retrieve units for
:type application_name: str
:returns: List of juju units
:rtype: [juju.unit.Unit, juju.unit.Unit,...]
"""
model = await get_model(model_name)
return model.applications[application_name].units
get_units = sync_wrapper(async_get_units)
async def async_get_machines(application_name, model_name=None):
"""Return all the machines of a given application.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application to retrieve units for
:type application_name: str
:returns: List of juju machines
:rtype: [juju.machine.Machine, juju.machine.Machine,...]
"""
model = await get_model(model_name)
machines = []
for unit in model.applications[application_name].units:
machines.append(unit.machine)
return machines
get_machines = sync_wrapper(async_get_machines)
def get_first_unit_name(application_name, model_name=None):
"""Return name of lowest numbered unit of given application.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application
:type application_name: str
:returns: Name of lowest numbered unit
:rtype: str
"""
return get_units(application_name, model_name=model_name)[0].name
async def async_get_lead_unit(application_name, model_name=None):
"""Return the leader unit for a given application.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application
:type application_name: str
:returns: Name of unit with leader status
:raises: zaza.utilities.exceptions.JujuError
"""
model = await get_model(model_name)
for unit in model.applications[application_name].units:
is_leader = await unit.is_leader_from_status()
if is_leader:
return unit
raise zaza_exceptions.JujuError("No leader found for application {}"
.format(application_name))
get_lead_unit = sync_wrapper(async_get_lead_unit)
async def async_get_lead_unit_name(application_name, model_name=None):
"""Return name of unit with leader status for given application.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application
:type application_name: str
:returns: Name of unit with leader status
:rtype: str
:raises: zaza.utilities.exceptions.JujuError
"""
return (await async_get_lead_unit(application_name, model_name)).entity_id
get_lead_unit_name = sync_wrapper(async_get_lead_unit_name)
async def async_get_unit_public_address(unit, model_name=None):
"""Get the public address of a unit.
Based on a feature flag "ZAZA_FEATURE_BUG472" existing, the function will
call `get_unit_public_address__libjuju()`. Otherwise, it will fall back to
using `get_unit_public_address__fallback()` so that the public address can
be extracted.
Bug: https://github.com/openstack-charmers/zaza/issues/472
:param unit: The libjuju unit object to get the public address for.
:type unit: juju.Unit
:returns: the IP address of the unit, or None
:rtype: Optional(str)
"""
if os.environ.get('ZAZA_FEATURE_BUG472', None):
return await async_get_unit_public_address__libjuju(
unit, model_name=model_name)
else:
return await async_get_unit_public_address__fallback(
unit, model_name=model_name)
get_unit_public_address = sync_wrapper(async_get_unit_public_address)
async def async_get_unit_public_address__libjuju(unit, model_name=None):
"""Get the public address of a unit.
The libjuju library, in theory, supports a unit.public_address attribute
that provides the publick address of the unit. However, when the unit is
an OpenStack VM, there is a race and it's possible it will be None.
Therefore, there is a 'get_public_address()' funtion on unit that does
provide the function. See [1].
Note, if the underlying provider hasn't provided an address (yet) then this
will return None.
1. https://github.com/juju/python-libjuju/issues/551
:param unit: The libjuju unit object to get the public address for.
:type unit: juju.Unit
:returns: the IP address of the unit.
:rtype: Optional(str)
"""
return await unit.get_public_address()
async def async_get_unit_public_address__fallback(unit, model_name=None):
"""Get the public address of a unit via juju status shell command.
Due to bug [1], this function calls juju status and extracts the public
address as provided by the juju go client, as libjuju is unreliable.
This is a stop-gap solution to work around the bug. If the IP address
can't be found, then None is returned.
[1]: https://github.com/juju/python-libjuju/issues/615
:param unit: The libjuju unit object to get the public address for.
:type unit: juju.Unit
:returns: the IP address of the unit.
:rtype: Optional[str]
"""
if model_name is None:
model_name = await async_get_juju_model()
cmd = "juju status --format=yaml -m {}".format(model_name)
result = await generic_utils.check_output(
cmd.split(), log_stderr=False, log_stdout=False)
status = yaml.safe_load(result['Stdout'])
try:
app = unit.name.split('/')[0]
return (
status['applications'][app]['units'][unit.name]['public-address'])
except KeyError:
logging.warn("Public address not found for %s", unit.name)
return None
async def async_get_app_ips(application_name, model_name=None):
"""Return public address of all units of an application.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application
:type application_name: str
:returns: List of ip addresses
:rtype: [str, str,...]
"""
addresses = []
for u in await async_get_units(application_name, model_name=model_name):
addresses.append(
await async_get_unit_public_address(u, model_name=model_name))
return addresses
get_app_ips = sync_wrapper(async_get_app_ips)
async def async_get_lead_unit_ip(application_name, model_name=None):
"""Return the IP address of the lead unit of a given application.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application
:type application_name: str
:returns: IP of the lead unit
:rtype: str
:raises: zaza.utilities.exceptions.JujuError
"""
return await async_get_unit_public_address(await async_get_lead_unit(
application_name, model_name))
get_lead_unit_ip = sync_wrapper(async_get_lead_unit_ip)
async def async_get_application_config(application_name, model_name=None):
"""Return application configuration.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application
:type application_name: str
:returns: Dictionary of configuration
:rtype: dict
"""
model = await get_model(model_name)
return await model.applications[application_name].get_config()
get_application_config = sync_wrapper(async_get_application_config)
async def async_reset_application_config(application_name, config_keys,
model_name=None):
"""Reset application configuration to default values.
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application
:type application_name: str
:param config_keys: List of configuration keys to reset to their defaults.
:type config_keys: List[str]
"""
model = await get_model(model_name)
return await (model.applications[application_name]
.reset_config(config_keys))
reset_application_config = sync_wrapper(async_reset_application_config)
async def async_set_application_config(application_name, configuration,
model_name=None):
"""Set application configuration.
NOTE: At the time of this writing python-libjuju requires all values passed
to `set_config` to be `str`.
https://github.com/juju/python-libjuju/issues/388
:param model_name: Name of model to query.
:type model_name: str
:param application_name: Name of application
:type application_name: str
:param configuration: Dictionary of configuration setting(s)
:type configuration: Dict[str,str]
"""
model = await get_model(model_name)
return await (model.applications[application_name]
.set_config(configuration))
set_application_config = sync_wrapper(async_set_application_config)
# A map of model names <-> last time get_status was called, and the result of
# that call.
_GET_STATUS_TIMES = {}
StatusResult = collections.namedtuple("StatusResult", ["time", "result"])
async def async_get_status(model_name=None, interval=4.0, refresh=True):
"""Return the full status, but share calls between different asyncs.
Return the full status for the model_name (current model is None), but no
faster than interval time, which is a default of 4 seconds. If refresh is
True, then this function waits until the interval is exceeded, and then