-
Notifications
You must be signed in to change notification settings - Fork 13
/
plugin.py
1668 lines (1440 loc) · 62.8 KB
/
plugin.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
import asyncio
import base64
import contextlib
import dataclasses
import enum
import grp
import inspect
import json
import logging
import os
import re
import shutil
import shlex
import subprocess
import sys
import textwrap
from collections import OrderedDict
from functools import cached_property
from fnmatch import fnmatch
from pathlib import Path
from random import choices
from string import ascii_lowercase, digits, hexdigits
from timeit import default_timer as timer
from typing import (
Generator,
Iterable,
List,
Literal,
MutableMapping,
Mapping,
Optional,
TypeVar,
Tuple,
Union,
)
from urllib.request import urlretrieve, urlopen
from urllib.parse import urlencode
from urllib.error import HTTPError
from zipfile import Path as ZipPath
import jinja2
import kubernetes.config
import pytest
import pytest_asyncio.plugin
import yaml
from _pytest.config import Config
from _pytest.config.argparsing import Parser
from kubernetes import client as k8s_client
from kubernetes.client import Configuration as K8sConfiguration
from juju.client import client
from juju.client.jujudata import FileJujuData
from juju.exceptions import DeadEntityException
from juju.errors import JujuError
from juju.model import Model, Controller, websockets
log = logging.getLogger(__name__)
def pytest_addoption(parser: Parser):
parser.addoption(
"--cloud",
action="store",
help="Juju cloud to use; if not provided, will "
"use the default for the controller",
)
parser.addoption(
"--controller",
action="store",
help="Juju controller to use; if not provided, "
"will use the current controller",
)
parser.addoption(
"--model-alias",
action="store",
help="Alias name used for the model created by ops_test",
default="main",
)
parser.addoption(
"--model",
action="store",
help="Juju model to use; if not provided, a new model "
"will be created for each test which requires one",
)
parser.addoption(
"--keep-models",
action="store_true",
help="Keep models handled by opstest, can be overriden in track_model",
)
parser.addoption(
"--destructive-mode",
action="store_true",
help="Whether to run charmcraft in destructive mode "
"(as opposed to doing builds in lxc containers)",
)
parser.addoption(
"--no-crash-dump",
action="store_true",
help="(Deprecated - use '--crash-dump=never' instead. Overrides anything"
" specified in '--crash-dump')\n"
"Disable automatic runs of juju-crashdump after failed tests, "
"juju-crashdump runs by default.",
)
parser.addoption(
"--crash-dump",
action="store",
default="legacy",
help="Sets whether to output a juju-crashdump after tests. Options are:\n"
"* always: dumps after all tests\n"
"* on-failure: dumps after failed tests\n"
"* legacy: (DEFAULT) dumps after a failed test if '--keep-models' is False\n"
"* never: never dumps",
)
parser.addoption(
"--crash-dump-args",
action="store",
default="",
help="If crashdump is run, run with provided extra arguments.",
)
parser.addoption(
"--crash-dump-output",
action="store",
default=None,
help="Store the completed crash dump in this dir. "
"The default is current working directory.",
)
parser.addoption(
"--no-deploy",
action="store_true",
help="This, together with the `--model` parameter, ensures that all functions "
"marked with the` skip_if_deployed` tag are skipped.",
)
parser.addoption(
"--model-config",
action="store",
default=None,
help="path to a yaml file which will be applied to the model on creation. "
"* ignored if `--model` supplied"
"* if the specified file doesn't exist, an error will be raised.",
)
def pytest_load_initial_conftests(parser: Parser, args: List[str]) -> None:
known_args = parser.parse_known_args(args)
if known_args.no_deploy and known_args.model is None:
optparser = parser._getparser()
optparser.error("must specify --model when using --no-deploy")
def pytest_configure(config: Config):
config.addinivalue_line("markers", "abort_on_fail")
config.addinivalue_line("markers", "skip_if_deployed")
if config.option.basetemp is None:
tox_dir = os.environ.get("TOX_ENV_DIR")
if tox_dir:
config.option.basetemp = Path(tox_dir) / "tmp/pytest"
def pytest_runtest_setup(item):
if (
"skip_if_deployed" in item.keywords
and item.config.getoption("--no-deploy")
and item.config.getoption("--model") is not None
):
pytest.skip("Skipping deployment because --no-deploy was specified.")
def check_deps(*deps):
missing = []
for dep in deps:
res = subprocess.run(["which", dep], capture_output=True)
if res.returncode != 0:
missing.append(dep)
if missing:
raise RuntimeError(
"Missing dependenc{}: {}".format(
"y" if len(missing) == 1 else "ies",
", ".join(missing),
)
)
@pytest.fixture(scope="module")
def event_loop():
"""Create an instance of the default event loop for each test module."""
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
# Plugin load order can't be set, replace asyncio directly
pytest_asyncio.plugin.event_loop = event_loop
def pytest_collection_modifyitems(session, config, items):
"""Automatically apply the "asyncio" marker to any async test items."""
for item in items:
is_async = inspect.iscoroutinefunction(getattr(item, "function", None))
has_marker = item.get_closest_marker("asyncio")
if is_async and not has_marker:
item.add_marker("asyncio")
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""Make test results available to fixture finalizers."""
# execute all other hooks to obtain the report object
outcome = yield
rep = outcome.get_result()
# set a report attribute for each phase of a call, which can
# be "setup", "call", "teardown"
setattr(item, "rep_" + rep.when, rep)
# set attribute which indicates fail / xfail in any phase
item.failed = getattr(item, "failed", False) or rep.failed
item.xfailed = getattr(item, "xfailed", False) or getattr(rep, "wasxfail", False)
@pytest.fixture(autouse=True)
def abort_on_fail(request):
if OpsTest._instance is None:
# If we don't have an ops_test already in play, this should be a no-op.
yield
return
ops_test = OpsTest._instance
if ops_test.aborted:
pytest.xfail("aborted")
yield
abort_on_fail = request.node.get_closest_marker("abort_on_fail")
failed = getattr(request.node, "failed", False)
if abort_on_fail and abort_on_fail.kwargs.get("abort_on_xfail", False):
failed = failed or request.node.xfailed
if failed and abort_on_fail:
ops_test.aborted = True
@pytest_asyncio.fixture(scope="module")
async def ops_test(request, tmp_path_factory):
check_deps("juju", "charmcraft")
ops_test = OpsTest(request, tmp_path_factory)
await ops_test._setup_model()
OpsTest._instance = ops_test
yield ops_test
OpsTest._instance = None
await ops_test._cleanup_models()
def handle_file_delete_error(function, path, execinfo):
log.warning(f"Failed to delete '{path}' due to {execinfo[1]}")
def validate_crash_dump(crash_dump: str, no_crash_dump: bool):
"""Validates the crash-dump inputs, raising if they are not accepted values."""
if no_crash_dump:
log.warning(
"Got flag --no-crash-dump. Ignoring value of flag --crash-dump and "
"setting --crash-dump=never"
)
crash_dump = "never"
accepted_crash_dump = ["always", "legacy", "on-failure", "never"]
if crash_dump not in accepted_crash_dump:
raise ValueError(
f"Got invalid --crash-dump={crash_dump}, must be one of"
f" {accepted_crash_dump}"
)
return crash_dump
class FileResource:
"""Represents a File based Resource."""
"""
Some resources are arch specific but don't include amd64 in the name
they'll be identified as being named <base><tail> where there is
another resource with <base>-<arch><tail>
"""
ARCH_RE = re.compile(r"^(\S+)(?:-(amd64|arm64|s390x))(\S+)?")
def __init__(self, name, filename, arch=None):
self.name = name
self.filename = filename
self.name_without_arch = self.name
self.arch = arch
matches = self.ARCH_RE.match(self.name)
if matches:
base, arch, tail = matches.groups()
self.name_without_arch = f"{base}{tail or ''}"
self.arch = arch
def __repr__(self):
return f"FileResource('{self.name}','{self.filename}','{self.arch}')"
@property
def download_path(self):
return Path(self.name) / self.filename
def json_request(url, params=None):
if params:
url = f"{url}?{urlencode(params)}"
with urlopen(url) as resp:
if 200 <= resp.status < 300:
return json.loads(resp.read())
class Charmhub:
"""
Fetch resources from Charmhub
API DOCS: https://api.snapcraft.io/docs/charms.html
"""
CH_URL = "https://api.charmhub.io/v2"
def __init__(self, charmhub_name, channel):
self._name = charmhub_name
self._channel = channel
@cached_property
def info(self):
params = dict(channel=self._channel, fields="default-release.resources")
url = f"{self.CH_URL}/charms/info/{self._name}"
try:
return json_request(url, params)
except HTTPError as ex:
raise RuntimeError(f"Charm {self._name} not found in charmhub.") from ex
@property
def exists(self):
try:
return bool(self.info)
except RuntimeError:
return False
@cached_property
def resource_map(self):
return {rsc["name"]: rsc for rsc in self.info["default-release"]["resources"]}
def download_resource(self, resource, destination: Path):
rsc = self.resource_map[resource]
log.info(f"Retrieving {resource} from charmhub...")
destination.parent.mkdir(parents=True, exist_ok=True)
target, _msg = urlretrieve(rsc["download"]["url"], destination)
return target
class CharmStore:
CS_URL = "https://api.jujucharms.com/charmstore/v5"
def __init__(self, charmstore_name, channel="edge"):
self._name = charmstore_name
self._channel = channel
@staticmethod
def _charmpath(charm):
if charm.startswith("cs:"):
return charm[3:]
return charm
@cached_property
def _charm_id(self):
params = dict(channel=self._channel)
url = f"{self.CS_URL}/{self._charmpath(self._name)}/meta/id"
try:
resp = json_request(url, params)
except HTTPError as ex:
raise RuntimeError(
f"Charm {self._name} not found in charmstore at channel={self._channel}"
) from ex
return resp["Id"]
@property
def exists(self):
try:
return bool(self._charm_id)
except RuntimeError:
return False
def download_resource(self, resource, destination: Path):
charm_id = self._charmpath(self._charm_id)
url = f"{self.CS_URL}/{charm_id}/meta/resources/{resource}"
try:
resp = json_request(url)
except HTTPError as ex:
raise RuntimeError(
f"Charm {charm_id} {resource} not found in charmstore"
) from ex
rev = resp["Revision"]
log.info(f"Retrieving {resource} from charmstore...")
url = f"{self.CS_URL}/{charm_id}/resource/{resource}/{rev}"
destination.parent.mkdir(parents=True, exist_ok=True)
local_file, header = urlretrieve(url, destination)
return local_file
class ModelNotFoundError(Exception):
"""Raise when referencing to a model that doesn't exist."""
class ModelInUseError(Exception):
"""Raise when trying to add a model alias which already exists."""
BundleOpt = Union[str, Path, "OpsTest.Bundle"]
Timeout = TypeVar("Timeout", float, int)
@dataclasses.dataclass
class ModelState:
model: Model
keep: bool
controller_name: str
cloud_name: Optional[str]
model_name: str
config: Optional[dict] = None
tmp_path: Optional[Path] = None
timeout: Optional[Timeout] = None
@property
def full_name(self) -> str:
return f"{self.controller_name}:{self.model_name}"
@dataclasses.dataclass
class CloudState:
cloud_name: str
models: List[str] = dataclasses.field(default_factory=list)
timeout: Optional[Timeout] = None
class OpsTest:
"""Utility class for testing Operator Charms."""
class ModelKeep(enum.Enum):
"""
Used to select the appropriate behavior for cleaning up models
created or used by ops_test.
"""
NEVER = "never"
"""
This gives pytest-operator the duty to delete this model
at the end of the test regardless of any outcome.
"""
ALWAYS = "always"
"""
This gives pytest-operator the duty to keep this model
at the end of the test regardless of any outcome.
"""
IF_EXISTS = "if-exists"
"""
If the model already exists before ops_test encounters it,
follow the rules defined by `track_model.use_existing`
* respects the --keep-models flag, otherwise
* newly created models mapped to ModelKeep.NEVER
* existing models mapped to ModelKeep.ALWAYS
"""
# store instance, so we can tell if it's been used yet
_instance: Optional["OpsTest"] = None
# objects can be created with `ops_test.Bundle(...)`
# since fixtures are autoloaded for pytest users,
# this exposes the class instantiation through
# ops_test.Bundle(...)
@dataclasses.dataclass
class Bundle:
"""Represents a charmhub bundle."""
name: str
channel: str = "stable"
arch: str = "all"
series: str = "all"
@property
def juju_download_args(self):
"""Create cli arguments used in juju download to download bundle to disk."""
return [
f"--{field.name}={getattr(self, field.name)}"
for field in dataclasses.fields(OpsTest.Bundle)
if field.default is not dataclasses.MISSING
]
def __init__(self, request, tmp_path_factory):
self.request = request
self._tmp_path_factory = tmp_path_factory
self._global_tmp_path = None
# Flag indicating whether all subsequent tests should be aborted.
self.aborted = False
# Flag for using destructive mode or not for charm builds.
self.destructive_mode = request.config.option.destructive_mode
# Config options to determine first model specs used by tests
self._orig_model_alias: Optional[str] = request.config.option.model_alias
self._init_cloud_name: Optional[str] = request.config.option.cloud
self._init_model_name: Optional[str] = request.config.option.model
self._init_keep_model: bool = request.config.option.keep_models
# These may be modified by _setup_model
self.controller_name = request.config.option.controller
self._init_model_config = request.config.option.model_config
# Flag for enabling the juju-crashdump
self.crash_dump = validate_crash_dump(
crash_dump=request.config.option.crash_dump,
no_crash_dump=request.config.option.no_crash_dump,
)
self.crash_dump_output = request.config.option.crash_dump_output
self.crash_dump_args = request.config.option.crash_dump_args
# These will be set by _setup_model
self.jujudata = None
self._controller: Optional[Controller] = None
# maintains a set of all models connected by this fixture
# use an OrderedDict so that the first model made is destroyed last.
self._current_alias = None
self._models: MutableMapping[str, ModelState] = OrderedDict()
self._clouds: MutableMapping[str, CloudState] = OrderedDict()
@contextlib.contextmanager
def model_context(self, alias: str) -> Generator[Model, None, None]:
"""
Analog to `juju switch` where the focus of the current model is moved.
"""
prior = self.current_alias
model = self._switch(alias)
try:
yield model
finally:
# if the there's a failure after yielding, don't fail to
# switch back to the prior alias but still raise whatever
# error condition occurred through the context
self._switch(prior, raise_not_found=False)
def _switch(self, alias: str, raise_not_found=True) -> Model:
if alias in self._models:
self._current_alias = alias
elif not raise_not_found:
self._current_alias = None
else:
raise ModelNotFoundError(f"{alias} not found")
return self.model
@property
def current_alias(self) -> Optional[str]:
return self._current_alias
@property
def models(self) -> Mapping[str, ModelState]:
"""Returns the dict of managed models by this fixture."""
return {k: dataclasses.replace(v) for k, v in self._models.items()}
@property
def tmp_path(self) -> Path:
tmp_path = self._global_tmp_path
current_state = self.current_alias and self._models.get(self.current_alias)
if current_state and current_state.tmp_path is None:
tmp_path = self._tmp_path_factory.mktemp(current_state.model_name)
current_state.tmp_path = tmp_path
elif current_state and current_state.tmp_path:
tmp_path = current_state.tmp_path
elif not tmp_path:
tmp_path = self._global_tmp_path = self._tmp_path_factory.mktemp(
self.default_model_name
)
log.info(f"Using tmp_path: {tmp_path}")
return tmp_path
@property
def model_config(self) -> Optional[dict]:
"""Represents the config used when adding the model."""
current_state = self.current_alias and self._models.get(self.current_alias)
return current_state.config if current_state else None
@property
def model(self) -> Optional[Model]:
"""Represents the current model."""
current_state = self.current_alias and self._models.get(self.current_alias)
return current_state.model if current_state else None
@property
def model_full_name(self) -> Optional[str]:
"""Represents the current model's full name."""
current_state = self.current_alias and self._models.get(self.current_alias)
return current_state.full_name if current_state else None
@property
def model_name(self) -> Optional[str]:
"""Represents the current model name."""
current_state = self.current_alias and self._models.get(self.current_alias)
return current_state.model_name if current_state else None
@property
def cloud_name(self) -> Optional[str]:
"""Represents the current model's cloud name."""
current_state = self.current_alias and self._models.get(self.current_alias)
return current_state.cloud_name if current_state else None
@property
def keep_model(self) -> bool:
"""Represents whether the current model should be kept after tests."""
current_state = self.current_alias and self._models.get(self.current_alias)
return current_state.keep if current_state else self._init_keep_model
def _generate_name(self, kind: str) -> str:
module_name = self.request.module.__name__.rpartition(".")[-1]
suffix = "".join(choices(ascii_lowercase + digits, k=4))
if kind != "model":
suffix = "-".join((kind, suffix))
return f"{module_name.replace('_', '-')}-{suffix}"
@cached_property
def default_model_name(self) -> str:
return self._generate_name(kind="model")
async def run(
self,
*cmd: str,
cwd: Optional[os.PathLike] = None,
check: bool = False,
fail_msg: Optional[str] = None,
stdin: Optional[bytes] = None,
) -> Tuple[Optional[int], str, str]:
"""Asynchronously run a subprocess command.
@param str cmd: command to execute within a juju context
@param Optional[os.Pathlink] cwd: current working directory
@param bool check: if False, returns a tuple (rc, stdout, stderr)
if True, calls `pytest.fail` with `fail_msg`
and relevant command information
@param Optional[str] fail_msg: Message to present if check=True and rc != 0
@param Optional[bytes] stdin: Bytes read by stdin of the called process
"""
env = {**os.environ}
if self.jujudata:
env["JUJU_DATA"] = self.jujudata.path
if self.model_full_name:
env["JUJU_MODEL"] = self.model_full_name
if not isinstance(stdin, bytes) and stdin is not None:
raise TypeError("'stdin' parameter must be a Optional[bytes] typed")
proc = await asyncio.create_subprocess_exec(
*(str(c) for c in cmd),
stdin=asyncio.subprocess.PIPE if isinstance(stdin, bytes) else None,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=str(cwd or "."),
env=env,
)
_stdout, _stderr = await proc.communicate(input=stdin)
stdout, stderr = _stdout.decode("utf8"), _stderr.decode("utf8")
if check and proc.returncode != 0:
if fail_msg is None:
fail_msg = f"Command {list(cmd)} failed"
raise AssertionError(
f"{fail_msg} ({proc.returncode}): {(stderr or stdout).strip()}"
)
return proc.returncode, stdout, stderr
_run = run # backward compatibility alias
async def juju(self, *args, **kwargs):
"""Runs a Juju CLI command.
Useful for cases where python-libjuju sees things differently than the Juju CLI.
Will set `JUJU_MODEL`, so manually passing in `-m model-name` is unnecessary.
"""
return await self.run("juju", *args, **kwargs)
async def _add_model(self, cloud_name, model_name, keep=False, **kwargs):
"""
Creates a model used by the test framework which would normally be destroyed
after the tests are run in the module.
"""
controller = self._controller
controller_name = controller.controller_name
credential_name = None
timeout = None
if not cloud_name:
# if not provided, try the default cloud name
cloud_name = self._init_cloud_name
if not cloud_name:
# if not provided, use the controller's default cloud
cloud_name = await controller.get_cloud()
if ops_cloud := self._clouds.get(cloud_name):
credential_name = cloud_name
timeout = ops_cloud.timeout
model_full_name = f"{controller_name}:{model_name}"
log.info(f"Adding model {model_full_name} on cloud {cloud_name}")
model = await controller.add_model(
model_name, cloud_name, credential_name=credential_name, **kwargs
)
# NB: This call to `juju models` is needed because libjuju's
# `add_model` doesn't update the models.yaml cache that the Juju
# CLI depends on with the model's UUID, which the CLI requires to
# connect. Calling `juju models` beforehand forces the CLI to
# update the cache from the controller.
await self.juju("models")
state = ModelState(
model, keep, controller_name, cloud_name, model_name, timeout=timeout
)
state.config = await model.get_config()
return state
async def _model_exists(self, model_name: str) -> bool:
"""
returns True when the model_name exists in the model.
"""
all_models = await self._controller.list_models()
return model_name in all_models
@staticmethod
async def _connect_to_model(controller_name, model_name, keep=True):
"""
Makes a reference to an existing model used by the test framework
which will not be destroyed after the tests are run in the module.
"""
model = Model()
state = ModelState(model, keep, controller_name, None, model_name)
log.info(
"Connecting to existing model %s on unspecified cloud", state.full_name
)
await model.connect(state.full_name)
state.config = await model.get_config()
return state
@staticmethod
def read_model_config(
config_path_or_obj: Union[dict, str, os.PathLike, None]
) -> Optional[dict]:
if isinstance(config_path_or_obj, dict):
return config_path_or_obj
model_config = None
if config_path_or_obj:
model_config_file = Path(config_path_or_obj)
if not model_config_file.exists():
log.error("model-config file %s doesn't exist", model_config_file)
raise FileNotFoundError(model_config_file)
else:
log.info("Loading model config from %s", model_config_file)
model_config = yaml.safe_load(model_config_file.read_text())
return model_config
async def _setup_model(self):
# TODO: We won't need this if Model.debug_log is implemented in libjuju
self.jujudata = FileJujuData()
alias = self._orig_model_alias
if not self.controller_name:
self.controller_name = self.jujudata.current_controller()
assert self.controller_name, "No controller selected for ops_test"
if not self._controller:
self._controller = Controller()
await self._controller.connect(self.controller_name)
await self.track_model(
alias,
model_name=self._init_model_name or self.default_model_name,
cloud_name=self._init_cloud_name,
keep=self._init_model_name is not None,
config=self.read_model_config(self._init_model_config),
)
self._current_alias = alias
async def track_model(
self,
alias: str,
model_name: Optional[str] = None,
cloud_name: Optional[str] = None,
use_existing: Optional[bool] = None,
keep: Union[ModelKeep, str, bool, None] = ModelKeep.IF_EXISTS,
**kwargs,
) -> Model:
"""
Track a new or existing model in the existing controller.
@param str alias : alias to the model used only by ops_test
to differentiate between models.
@param Optional[str] model_name: name of the new model to track,
None will craft a unique name
@param Optional[str] cloud_name: cloud name in which to add a new model,
None will use current cloud
@param Optional[bool] use_existing:
None: True if model_name exists on this controller
False: create a new model and keep=False, unless keep=True explicitly set
True: connect to a model and keep=True, unless keep=False explicitly set
@param Optional[ModelKeep, str, bool, None] keep:
ModelKeep : See docs for the enum
str : mapped to ModelKeep values
None : Same as ModelKeep.IF_EXISTS
True : Same as ModelKeep.ALWAYS
False : Same as ModelKeep.NEVER, but respects keep-models flag
Common Examples:
----------------------------------
# make a new model with any juju name and destroy it when the tests are over
await ops_test.track_model("alias")
# make or reuse a model known to juju as "bob"
# don't destroy model if it existed, destroy it if it didn't already exist
await ops_test.track_model("alias", model_name="bob")
----------------------------------
"""
if alias in self._models:
raise ModelInUseError(f"Cannot add new model with alias '{alias}'")
if model_name and use_existing is None:
use_existing = await self._model_exists(model_name)
keep_val: bool = False
if isinstance(keep, str):
keep = OpsTest.ModelKeep(keep.lower())
if isinstance(keep, OpsTest.ModelKeep):
if keep is OpsTest.ModelKeep.IF_EXISTS:
keep_val = self._init_keep_model or bool(use_existing)
elif keep is OpsTest.ModelKeep.ALWAYS:
keep_val = True
elif keep is OpsTest.ModelKeep.NEVER:
keep_val = False
elif isinstance(keep, bool):
keep_val = self._init_keep_model or keep
elif keep is None:
keep_val = self._init_keep_model or bool(use_existing)
if use_existing:
if not model_name:
raise NotImplementedError(
"Cannot use_existing model if model_name is unspecified"
)
model_state = await self._connect_to_model(
self.controller_name, model_name, keep_val
)
else:
cloud_name = cloud_name or self.cloud_name
model_name = model_name or self._generate_name(kind="model")
model_state = await self._add_model(
cloud_name, model_name, keep_val, **kwargs
)
self._models[alias] = model_state
if ops_cloud := self._clouds.get(cloud_name):
ops_cloud.models.append(alias)
return model_state.model
async def log_model(self):
"""Log a summary of the status of the model."""
# TODO: Implement a pretty model status in libjuju
_, stdout, _ = await self.juju("status")
log.info(f"Model status:\n\n{stdout}")
# TODO: Implement Model.debug_log in libjuju
_, stdout, _ = await self.juju(
"debug-log", "--replay", "--no-tail", "--level", "ERROR"
)
log.info(f"Juju error logs:\n\n{stdout}")
async def create_crash_dump(self) -> bool:
"""Run the juju-crashdump if it's possible."""
args = ["-s", f"-m={self.model_full_name}", "-a=debug-layer", "-a=config"]
output_directory = self.crash_dump_output
if output_directory:
log.debug("juju-crashdump will use output dir `%s`", output_directory)
args.append(f"-o={output_directory}")
user_args = shlex.split(self.crash_dump_args)
cmd = ["juju-crashdump"] + args + user_args
try:
return_code, _, __ = await self.run(*cmd)
log.info("juju-crashdump finished [%s]", return_code)
return True
except FileNotFoundError:
log.info("juju-crashdump command was not found.")
return False
async def forget_model(
self,
alias: Optional[str] = None,
timeout: Optional[Timeout] = None,
allow_failure: bool = True,
destroy_storage: bool = False,
):
"""
Forget a model and wait for it to be removed from the controller.
If the model is marked as kept, ops_tests forgets about this model immediately.
If the model is not marked as kept, ops_test will destroy the model.
If timeout is None don't wait on the model to be completely destroyed
@param str alias: alias of the model (default: current alias)
@param Optional[float,int] timeout: how long to wait for it to be removed,
if None, don't block waiting for success
@param bool allow_failure: if False, failures raise an exception
@param bool destroy_storage: destroy storage when removing model
"""
if not self._controller:
log.error("No access to controller, skipping...")
return
if not alias:
alias = self.current_alias
if alias not in self.models:
raise ModelNotFoundError(f"{alias} not found")
model_state: ModelState = self._models[alias]
if timeout is None and model_state.timeout:
timeout = model_state.timeout
async def is_model_alive():
return model_name in await self._controller.list_models()
with self.model_context(alias) as model:
await self.log_model()
model_name = model.info.name
if self.is_crash_dump_enabled():
await self.create_crash_dump()
if not self.keep_model:
await self._reset(model, allow_failure, timeout=timeout)
await self._controller.destroy_model(
model_name,
force=True,
destroy_storage=destroy_storage,
max_wait=timeout,
)
if timeout and await is_model_alive():
log.warning("Waiting for model %s to die...", model_name)
while await is_model_alive():
await asyncio.sleep(5)
await model.disconnect()
# stop managing this model now
log.info(f"Forgetting model {alias}...")
self._models.pop(alias)
if ops_cloud := self._clouds.get(model_state.cloud_name):
ops_cloud.models.remove(alias)
if alias is self.current_alias:
self._current_alias = None
@staticmethod
async def _reset(model: Model, allow_failure, timeout: Optional[Timeout] = None):
# Forcibly destroy applications/machines in case any units are in error.
async def _destroy(entity_name: str, **kwargs):
for key, entity in getattr(model, entity_name).items():
try:
log.info(f" Destroying {entity_name} {key}")
await entity.destroy(**kwargs)
except DeadEntityException as e:
log.warning(e)
log.warning(f"{entity_name.title()} already dead, skipping")
except JujuError as e:
log.exception(e)
if not allow_failure:
raise
return None
log.info(f"Resetting model {model.info.name}...")
await _destroy("applications")
await _destroy("machines", force=True)
if timeout is None:
log.info("Not waiting on reset to complete.")
return
try:
await model.block_until(
lambda: len(model.units) == 0
and len(model.machines) == 0
and len(model.applications) == 0,
timeout=timeout,
)
except asyncio.TimeoutError:
log.exception(f"Timeout resetting {model.info.name}")
if not allow_failure:
raise
except websockets.ConnectionClosed:
log.error(f"Disconnected while resetting {model.info.name}")
if not allow_failure:
raise
else:
log.info(f"Reset {model.info.name} completed successfully.")
async def _cleanup_models(self):
# remove clouds from most recently made, to first made
# each model in the cloud will be forgotten
for cloud in reversed(self._clouds):