-
Notifications
You must be signed in to change notification settings - Fork 25
/
base.py
1436 lines (1156 loc) · 44.3 KB
/
base.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
# -*- coding: utf-8 -*-
"""Base class for AYON addons."""
import copy
import os
import sys
import time
import inspect
import logging
import threading
import collections
from uuid import uuid4
from abc import ABCMeta, abstractmethod
import six
import appdirs
from ayon_core.lib import Logger
from ayon_core.client import get_ayon_server_api_connection
from ayon_core.settings import get_system_settings
from ayon_core.settings.ayon_settings import (
is_dev_mode_enabled,
get_ayon_settings,
)
from .interfaces import (
IPluginPaths,
IHostAddon,
ITrayAddon,
ITrayService
)
# Files that will be always ignored on addons import
IGNORED_FILENAMES = (
"__pycache__",
)
# Files ignored on addons import from "./ayon_core/modules"
IGNORED_DEFAULT_FILENAMES = (
"__init__.py",
"base.py",
"interfaces.py",
"click_wrap.py",
"example_addons",
"default_modules",
)
IGNORED_HOSTS_IN_AYON = {
"flame",
"harmony",
}
IGNORED_MODULES_IN_AYON = set()
# Inherit from `object` for Python 2 hosts
class _ModuleClass(object):
"""Fake module class for storing AYON addons.
Object of this class can be stored to `sys.modules` and used for storing
dynamically imported modules.
"""
def __init__(self, name):
# Call setattr on super class
super(_ModuleClass, self).__setattr__("name", name)
super(_ModuleClass, self).__setattr__("__name__", name)
# Where modules and interfaces are stored
super(_ModuleClass, self).__setattr__("__attributes__", dict())
super(_ModuleClass, self).__setattr__("__defaults__", set())
super(_ModuleClass, self).__setattr__("_log", None)
def __getattr__(self, attr_name):
if attr_name not in self.__attributes__:
if attr_name in ("__path__", "__file__"):
return None
raise AttributeError("'{}' has not attribute '{}'".format(
self.name, attr_name
))
return self.__attributes__[attr_name]
def __iter__(self):
for module in self.values():
yield module
def __setattr__(self, attr_name, value):
if attr_name in self.__attributes__:
self.log.warning(
"Duplicated name \"{}\" in {}. Overriding.".format(
attr_name, self.name
)
)
self.__attributes__[attr_name] = value
def __setitem__(self, key, value):
self.__setattr__(key, value)
def __getitem__(self, key):
return getattr(self, key)
@property
def log(self):
if self._log is None:
super(_ModuleClass, self).__setattr__(
"_log", Logger.get_logger(self.name)
)
return self._log
def get(self, key, default=None):
return self.__attributes__.get(key, default)
def keys(self):
return self.__attributes__.keys()
def values(self):
return self.__attributes__.values()
def items(self):
return self.__attributes__.items()
class _LoadCache:
addons_lock = threading.Lock()
addons_loaded = False
def load_addons(force=False):
"""Load AYON addons as python modules.
Modules does not load only classes (like in Interfaces) because there must
be ability to use inner code of addon and be able to import it from one
defined place.
With this it is possible to import addon's content from predefined module.
Args:
force (bool): Force to load addons even if are already loaded.
This won't update already loaded and used (cached) modules.
"""
if _LoadCache.addons_loaded and not force:
return
if not _LoadCache.addons_lock.locked():
with _LoadCache.addons_lock:
_load_addons()
_LoadCache.addons_loaded = True
else:
# If lock is locked wait until is finished
while _LoadCache.addons_lock.locked():
time.sleep(0.1)
def _get_ayon_bundle_data():
con = get_ayon_server_api_connection()
bundles = con.get_bundles()["bundles"]
bundle_name = os.getenv("AYON_BUNDLE_NAME")
return next(
(
bundle
for bundle in bundles
if bundle["name"] == bundle_name
),
None
)
def _get_ayon_addons_information(bundle_info):
"""Receive information about addons to use from server.
Todos:
Actually ask server for the information.
Allow project name as optional argument to be able to query information
about used addons for specific project.
Returns:
List[Dict[str, Any]]: List of addon information to use.
"""
output = []
bundle_addons = bundle_info["addons"]
con = get_ayon_server_api_connection()
addons = con.get_addons_info()["addons"]
for addon in addons:
name = addon["name"]
versions = addon.get("versions")
addon_version = bundle_addons.get(name)
if addon_version is None or not versions:
continue
version = versions.get(addon_version)
if version:
version = copy.deepcopy(version)
version["name"] = name
version["version"] = addon_version
output.append(version)
return output
def _load_ayon_addons(openpype_modules, modules_key, log):
"""Load AYON addons based on information from server.
This function should not trigger downloading of any addons but only use
what is already available on the machine (at least in first stages of
development).
Args:
openpype_modules (_ModuleClass): Module object where modules are
stored.
modules_key (str): Key under which will be modules imported in
`sys.modules`.
log (logging.Logger): Logger object.
Returns:
List[str]: List of v3 addons to skip to load because v4 alternative is
imported.
"""
addons_to_skip_in_core = []
bundle_info = _get_ayon_bundle_data()
addons_info = _get_ayon_addons_information(bundle_info)
if not addons_info:
return addons_to_skip_in_core
addons_dir = os.environ.get("AYON_ADDONS_DIR")
if not addons_dir:
addons_dir = os.path.join(
appdirs.user_data_dir("AYON", "Ynput"),
"addons"
)
dev_mode_enabled = is_dev_mode_enabled()
dev_addons_info = {}
if dev_mode_enabled:
# Get dev addons info only when dev mode is enabled
dev_addons_info = bundle_info.get("addonDevelopment", dev_addons_info)
addons_dir_exists = os.path.exists(addons_dir)
if not addons_dir_exists:
log.warning("Addons directory does not exists. Path \"{}\"".format(
addons_dir
))
for addon_info in addons_info:
addon_name = addon_info["name"]
addon_version = addon_info["version"]
# core addon does not have any addon object
if addon_name in ("openpype", "core"):
continue
dev_addon_info = dev_addons_info.get(addon_name, {})
use_dev_path = dev_addon_info.get("enabled", False)
addon_dir = None
if use_dev_path:
addon_dir = dev_addon_info["path"]
if not addon_dir or not os.path.exists(addon_dir):
log.warning((
"Dev addon {} {} path does not exists. Path \"{}\""
).format(addon_name, addon_version, addon_dir))
continue
elif addons_dir_exists:
folder_name = "{}_{}".format(addon_name, addon_version)
addon_dir = os.path.join(addons_dir, folder_name)
if not os.path.exists(addon_dir):
log.debug((
"No localized client code found for addon {} {}."
).format(addon_name, addon_version))
continue
if not addon_dir:
continue
sys.path.insert(0, addon_dir)
imported_modules = []
for name in os.listdir(addon_dir):
# Ignore of files is implemented to be able to run code from code
# where usually is more files than just the addon
# Ignore start and setup scripts
if name in ("setup.py", "start.py", "__pycache__"):
continue
path = os.path.join(addon_dir, name)
basename, ext = os.path.splitext(name)
# Ignore folders/files with dot in name
# - dot names cannot be imported in Python
if "." in basename:
continue
is_dir = os.path.isdir(path)
is_py_file = ext.lower() == ".py"
if not is_py_file and not is_dir:
continue
try:
mod = __import__(basename, fromlist=("",))
for attr_name in dir(mod):
attr = getattr(mod, attr_name)
if (
inspect.isclass(attr)
and issubclass(attr, AYONAddon)
):
imported_modules.append(mod)
break
except BaseException:
log.warning(
"Failed to import \"{}\"".format(basename),
exc_info=True
)
if not imported_modules:
log.warning("Addon {} {} has no content to import".format(
addon_name, addon_version
))
continue
if len(imported_modules) > 1:
log.warning((
"Skipping addon '{}'."
" Multiple modules were found ({}) in dir {}."
).format(
addon_name,
", ".join([m.__name__ for m in imported_modules]),
addon_dir,
))
continue
mod = imported_modules[0]
addon_alias = getattr(mod, "V3_ALIAS", None)
if not addon_alias:
addon_alias = addon_name
addons_to_skip_in_core.append(addon_alias)
new_import_str = "{}.{}".format(modules_key, addon_alias)
sys.modules[new_import_str] = mod
setattr(openpype_modules, addon_alias, mod)
return addons_to_skip_in_core
def _load_addons_in_core(
ignore_addon_names, openpype_modules, modules_key, log
):
# Add current directory at first place
# - has small differences in import logic
current_dir = os.path.abspath(os.path.dirname(__file__))
hosts_dir = os.path.join(os.path.dirname(current_dir), "hosts")
modules_dir = os.path.join(os.path.dirname(current_dir), "modules")
ignored_host_names = set(IGNORED_HOSTS_IN_AYON)
ignored_module_dir_filenames = (
set(IGNORED_DEFAULT_FILENAMES)
| IGNORED_MODULES_IN_AYON
)
for dirpath in {hosts_dir, modules_dir}:
if not os.path.exists(dirpath):
log.warning((
"Could not find path when loading AYON addons \"{}\""
).format(dirpath))
continue
is_in_modules_dir = dirpath == modules_dir
if is_in_modules_dir:
ignored_filenames = ignored_module_dir_filenames
else:
ignored_filenames = ignored_host_names
for filename in os.listdir(dirpath):
# Ignore filenames
if filename in IGNORED_FILENAMES or filename in ignored_filenames:
continue
fullpath = os.path.join(dirpath, filename)
basename, ext = os.path.splitext(filename)
if basename in ignore_addon_names:
continue
# Validations
if os.path.isdir(fullpath):
# Check existence of init file
init_path = os.path.join(fullpath, "__init__.py")
if not os.path.exists(init_path):
log.debug((
"Addon directory does not contain __init__.py"
" file {}"
).format(fullpath))
continue
elif ext not in (".py", ):
continue
# TODO add more logic how to define if folder is addon or not
# - check manifest and content of manifest
try:
# Don't import dynamically current directory modules
new_import_str = "{}.{}".format(modules_key, basename)
if is_in_modules_dir:
import_str = "ayon_core.modules.{}".format(basename)
default_module = __import__(import_str, fromlist=("", ))
sys.modules[new_import_str] = default_module
setattr(openpype_modules, basename, default_module)
else:
import_str = "ayon_core.hosts.{}".format(basename)
# Until all hosts are converted to be able use them as
# modules is this error check needed
try:
default_module = __import__(
import_str, fromlist=("", )
)
sys.modules[new_import_str] = default_module
setattr(openpype_modules, basename, default_module)
except Exception:
log.warning(
"Failed to import host folder {}".format(basename),
exc_info=True
)
except Exception:
if is_in_modules_dir:
msg = "Failed to import in-core addon '{}'.".format(
basename
)
else:
msg = "Failed to import addon '{}'.".format(fullpath)
log.error(msg, exc_info=True)
def _load_addons():
# Support to use 'openpype' imports
sys.modules["openpype"] = sys.modules["ayon_core"]
# Key under which will be modules imported in `sys.modules`
modules_key = "openpype_modules"
# Change `sys.modules`
sys.modules[modules_key] = openpype_modules = _ModuleClass(modules_key)
log = Logger.get_logger("AddonsLoader")
ignore_addon_names = _load_ayon_addons(
openpype_modules, modules_key, log
)
_load_addons_in_core(
ignore_addon_names, openpype_modules, modules_key, log
)
_MARKING_ATTR = "_marking"
def mark_func(func):
"""Mark function to be used in report.
Args:
func (Callable): Function to mark.
Returns:
Callable: Marked function.
"""
setattr(func, _MARKING_ATTR, True)
return func
def is_func_marked(func):
return getattr(func, _MARKING_ATTR, False)
@six.add_metaclass(ABCMeta)
class AYONAddon(object):
"""Base class of AYON addon.
Attributes:
id (UUID): Addon object id.
enabled (bool): Is addon enabled.
name (str): Addon name.
Args:
manager (AddonsManager): Manager object who discovered addon.
settings (dict[str, Any]): AYON settings.
"""
enabled = True
_id = None
def __init__(self, manager, settings):
self.manager = manager
self.log = Logger.get_logger(self.name)
self.initialize(settings)
@property
def id(self):
"""Random id of addon object.
Returns:
str: Object id.
"""
if self._id is None:
self._id = uuid4()
return self._id
@property
@abstractmethod
def name(self):
"""Addon name.
Returns:
str: Addon name.
"""
pass
def initialize(self, settings):
"""Initialization of addon attributes.
It is not recommended to override __init__ that's why specific method
was implemented.
Args:
settings (dict[str, Any]): Settings.
"""
pass
@mark_func
def connect_with_addons(self, enabled_addons):
"""Connect with other enabled addons.
Args:
enabled_addons (list[AYONAddon]): Addons that are enabled.
"""
pass
def get_global_environments(self):
"""Get global environments values of addon.
Environment variables that can be get only from system settings.
Returns:
dict[str, str]: Environment variables.
"""
return {}
def modify_application_launch_arguments(self, application, env):
"""Give option to modify launch environments before application launch.
Implementation is optional. To change environments modify passed
dictionary of environments.
Args:
application (Application): Application that is launched.
env (dict[str, str]): Current environment variables.
"""
pass
def on_host_install(self, host, host_name, project_name):
"""Host was installed which gives option to handle in-host logic.
It is a good option to register in-host event callbacks which are
specific for the addon. The addon is kept in memory for rest of
the process.
Arguments may change in future. E.g. 'host_name' should be possible
to receive from 'host' object.
Args:
host (Union[ModuleType, HostBase]): Access to installed/registered
host object.
host_name (str): Name of host.
project_name (str): Project name which is main part of host
context.
"""
pass
def cli(self, addon_click_group):
"""Add commands to click group.
The best practise is to create click group for whole addon which is
used to separate commands.
Example:
class MyPlugin(AYONAddon):
...
def cli(self, addon_click_group):
addon_click_group.add_command(cli_main)
@click.group(<addon name>, help="<Any help shown in cmd>")
def cli_main():
pass
@cli_main.command()
def mycommand():
print("my_command")
Args:
addon_click_group (click.Group): Group to which can be added
commands.
"""
pass
class OpenPypeModule(AYONAddon):
"""Base class of OpenPype module.
Deprecated:
Use `AYONAddon` instead.
Args:
manager (AddonsManager): Manager object who discovered addon.
settings (dict[str, Any]): Module settings (OpenPype settings).
"""
# Disable by default
enabled = False
class OpenPypeAddOn(OpenPypeModule):
# Enable Addon by default
enabled = True
class AddonsManager:
"""Manager of addons that helps to load and prepare them to work.
Args:
settings (Optional[dict[str, Any]]): AYON studio settings.
initialize (Optional[bool]): Initialize addons on init.
True by default.
"""
# Helper attributes for report
_report_total_key = "Total"
_log = None
def __init__(self, settings=None, initialize=True):
self._settings = settings
self._system_settings = None
self._addons = []
self._addons_by_id = {}
self._addons_by_name = {}
# For report of time consumption
self._report = {}
if initialize:
self.initialize_addons()
self.connect_addons()
def __getitem__(self, addon_name):
return self._addons_by_name[addon_name]
@property
def log(self):
if self._log is None:
self._log = logging.getLogger(self.__class__.__name__)
return self._log
def get(self, addon_name, default=None):
"""Access addon by name.
Args:
addon_name (str): Name of addon which should be returned.
default (Any): Default output if addon is not available.
Returns:
Union[AYONAddon, Any]: Addon found by name or `default`.
"""
return self._addons_by_name.get(addon_name, default)
@property
def addons(self):
return list(self._addons)
@property
def addons_by_id(self):
return dict(self._addons_by_id)
@property
def addons_by_name(self):
return dict(self._addons_by_name)
def get_enabled_addon(self, addon_name, default=None):
"""Fast access to enabled addon.
If addon is available but is not enabled default value is returned.
Args:
addon_name (str): Name of addon which should be returned.
default (Any): Default output if addon is not available or is
not enabled.
Returns:
Union[AYONAddon, None]: Enabled addon found by name or None.
"""
addon = self.get(addon_name)
if addon is not None and addon.enabled:
return addon
return default
def get_enabled_addons(self):
"""Enabled addons initialized by the manager.
Returns:
list[AYONAddon]: Initialized and enabled addons.
"""
return [
addon
for addon in self._addons
if addon.enabled
]
def initialize_addons(self):
"""Import and initialize addons."""
# Make sure modules are loaded
load_addons()
import openpype_modules
self.log.debug("*** AYON addons initialization.")
# Prepare settings for addons
settings = self._settings
if settings is None:
settings = get_ayon_settings()
# OpenPype settings
system_settings = self._system_settings
if system_settings is None:
system_settings = get_system_settings()
modules_settings = system_settings["modules"]
report = {}
time_start = time.time()
prev_start_time = time_start
addon_classes = []
for module in openpype_modules:
# Go through globals in `pype.modules`
for name in dir(module):
modules_item = getattr(module, name, None)
# Filter globals that are not classes which inherit from
# AYONAddon
if (
not inspect.isclass(modules_item)
or modules_item is AYONAddon
or modules_item is OpenPypeModule
or modules_item is OpenPypeAddOn
or not issubclass(modules_item, AYONAddon)
):
continue
# Check if class is abstract (Developing purpose)
if inspect.isabstract(modules_item):
# Find abstract attributes by convention on `abc` module
not_implemented = []
for attr_name in dir(modules_item):
attr = getattr(modules_item, attr_name, None)
abs_method = getattr(
attr, "__isabstractmethod__", None
)
if attr and abs_method:
not_implemented.append(attr_name)
# Log missing implementations
self.log.warning((
"Skipping abstract Class: {}."
" Missing implementations: {}"
).format(name, ", ".join(not_implemented)))
continue
addon_classes.append(modules_item)
aliased_names = []
for addon_cls in addon_classes:
name = addon_cls.__name__
if issubclass(addon_cls, OpenPypeModule):
# TODO change to warning
self.log.debug((
"Addon '{}' is inherited from 'OpenPypeModule'."
" Please use 'AYONAddon'."
).format(name))
try:
# Try initialize module
if issubclass(addon_cls, OpenPypeModule):
addon = addon_cls(self, modules_settings)
else:
addon = addon_cls(self, settings)
# Store initialized object
self._addons.append(addon)
self._addons_by_id[addon.id] = addon
self._addons_by_name[addon.name] = addon
# NOTE This will be removed with release 1.0.0 of ayon-core
# please use carefully.
# Gives option to use alias name for addon for cases when
# name in OpenPype was not the same as in AYON.
name_alias = getattr(addon, "openpype_alias", None)
if name_alias:
aliased_names.append((name_alias, addon))
enabled_str = "X"
if not addon.enabled:
enabled_str = " "
self.log.debug("[{}] {}".format(enabled_str, name))
now = time.time()
report[addon.__class__.__name__] = now - prev_start_time
prev_start_time = now
except Exception:
self.log.warning(
"Initialization of addon '{}' failed.".format(name),
exc_info=True
)
for item in aliased_names:
name_alias, addon = item
if name_alias not in self._addons_by_name:
self._addons_by_name[name_alias] = addon
continue
self.log.warning(
"Alias name '{}' of addon '{}' is already assigned.".format(
name_alias, addon.name
)
)
if self._report is not None:
report[self._report_total_key] = time.time() - time_start
self._report["Initialization"] = report
def connect_addons(self):
"""Trigger connection with other enabled addons.
Addons should handle their interfaces in `connect_with_addons`.
"""
report = {}
time_start = time.time()
prev_start_time = time_start
enabled_modules = self.get_enabled_addons()
self.log.debug("Has {} enabled modules.".format(len(enabled_modules)))
for module in enabled_modules:
try:
if not is_func_marked(module.connect_with_addons):
module.connect_with_addons(enabled_modules)
elif hasattr(module, "connect_with_modules"):
self.log.warning((
"DEPRECATION WARNING: Addon '{}' still uses"
" 'connect_with_modules' method. Please switch to use"
" 'connect_with_addons' method."
).format(module.name))
module.connect_with_modules(enabled_modules)
except Exception:
self.log.error(
"BUG: Module failed on connection with other modules.",
exc_info=True
)
now = time.time()
report[module.__class__.__name__] = now - prev_start_time
prev_start_time = now
if self._report is not None:
report[self._report_total_key] = time.time() - time_start
self._report["Connect modules"] = report
def collect_global_environments(self):
"""Helper to collect global environment variabled from modules.
Returns:
dict: Global environment variables from enabled modules.
Raises:
AssertionError: Global environment variables must be unique for
all modules.
"""
module_envs = {}
for module in self.get_enabled_addons():
# Collect global module's global environments
_envs = module.get_global_environments()
for key, value in _envs.items():
if key in module_envs:
# TODO better error message
raise AssertionError(
"Duplicated environment key {}".format(key)
)
module_envs[key] = value
return module_envs
def collect_plugin_paths(self):
"""Helper to collect all plugins from modules inherited IPluginPaths.
Unknown keys are logged out.
Returns:
dict: Output is dictionary with keys "publish", "create", "load",
"actions" and "inventory" each containing list of paths.
"""
# Output structure
output = {
"publish": [],
"create": [],
"load": [],
"actions": [],
"inventory": []
}
unknown_keys_by_addon = {}
for addon in self.get_enabled_addons():
# Skip module that do not inherit from `IPluginPaths`
if not isinstance(addon, IPluginPaths):
continue
plugin_paths = addon.get_plugin_paths()
for key, value in plugin_paths.items():
# Filter unknown keys
if key not in output:
if addon.name not in unknown_keys_by_addon:
unknown_keys_by_addon[addon.name] = []
unknown_keys_by_addon[addon.name].append(key)
continue
# Skip if value is empty
if not value:
continue
# Convert to list if value is not list
if not isinstance(value, (list, tuple, set)):
value = [value]
output[key].extend(value)
# Report unknown keys (Developing purposes)
if unknown_keys_by_addon:
expected_keys = ", ".join([
"\"{}\"".format(key) for key in output.keys()
])
msg_template = "Addon: \"{}\" - got key {}"
msg_items = []
for addon_name, keys in unknown_keys_by_addon.items():
joined_keys = ", ".join([
"\"{}\"".format(key) for key in keys
])
msg_items.append(msg_template.format(addon_name, joined_keys))
self.log.warning((
"Expected keys from `get_plugin_paths` are {}. {}"
).format(expected_keys, " | ".join(msg_items)))
return output
def _collect_plugin_paths(self, method_name, *args, **kwargs):
output = []
for addon in self.get_enabled_addons():
# Skip addon that do not inherit from `IPluginPaths`
if not isinstance(addon, IPluginPaths):
continue
method = getattr(addon, method_name)
try:
paths = method(*args, **kwargs)
except Exception:
self.log.warning(
(
"Failed to get plugin paths from addon"
" '{}' using '{}'."
).format(addon.__class__.__name__, method_name),
exc_info=True
)
continue
if paths:
# Convert to list if value is not list
if not isinstance(paths, (list, tuple, set)):
paths = [paths]
output.extend(paths)
return output
def collect_create_plugin_paths(self, host_name):
"""Helper to collect creator plugin paths from addons.
Args:
host_name (str): For which host are creators meant.
Returns:
list: List of creator plugin paths.
"""