You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

hook.py 5.1 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Hook module."""
  16. import os
  17. import stat
  18. import threading
  19. from importlib import import_module
  20. from mindinsight.conf import settings
  21. from mindinsight.utils.exceptions import FileSystemPermissionError
  22. class BaseHook:
  23. """Base hook class."""
  24. def register_secure_domains(self):
  25. """Hook function to register secure domains."""
  26. return []
  27. def register_startup_arguments(self, parser):
  28. """
  29. Hook function to register startup arguments.
  30. Args:
  31. parser (ArgumentParser): specify parser to which arguments are added.
  32. """
  33. def on_startup(self, logger):
  34. """
  35. Hook function to on startup.
  36. Args:
  37. logger (Logger): script logger of start command.
  38. """
  39. def on_shutdown(self, logger):
  40. """
  41. Hook function to on shutdown.
  42. Args:
  43. logger (Logger): script logger of stop command.
  44. """
  45. def on_init(self):
  46. """Hook function to on init."""
  47. class HookUtils:
  48. """
  49. Lock utilities.
  50. Examples:
  51. >>> from mindinsight.utils.hook import HookUtils
  52. >>> for hook in HookUtils.instance().hooks():
  53. >>> domains = hook.register_secure_domains()
  54. >>> hook.register_startup_arguments(parser)
  55. >>> hook.on_startup(logger)
  56. >>> hook.on_shutdown(logger)
  57. >>> hook.on_init()
  58. """
  59. _lock = threading.Lock()
  60. _instance = None
  61. def __new__(cls, *args, **kwargs):
  62. """Built-in __new__ function."""
  63. if cls._instance is None:
  64. with cls._lock:
  65. if cls._instance is None:
  66. cls._instance = super().__new__(cls, *args, **kwargs)
  67. cls._instance.discover()
  68. return cls._instance
  69. def discover(self):
  70. """Discover hook instances."""
  71. self.__hooks = []
  72. mindinsight_path = os.path.join(__file__, os.pardir, os.pardir)
  73. hook_path = os.path.realpath(os.path.join(mindinsight_path, 'common', 'hook'))
  74. files = os.listdir(hook_path)
  75. files.sort()
  76. for file in files:
  77. if file.startswith('_') or not file.endswith('.py'):
  78. continue
  79. hook_name = file[:-len('.py')]
  80. hook_module = import_module('mindinsight.common.hook.{}'.format(hook_name))
  81. hook_cls = getattr(hook_module, 'Hook', None)
  82. if hook_cls is not None and issubclass(hook_cls, BaseHook):
  83. self.__hooks.append(hook_cls())
  84. def hooks(self):
  85. """
  86. Return list of hook instances.
  87. Returns:
  88. list, list of hook instances.
  89. """
  90. return self.__hooks
  91. @classmethod
  92. def instance(cls):
  93. """
  94. Produce singleton instance of HookUtils.
  95. Returns:
  96. HookUtils, singleton instance of HookUtils.
  97. """
  98. if cls._instance is None:
  99. cls._instance = cls()
  100. return cls._instance
  101. def init(workspace='', config='', **kwargs):
  102. """
  103. Init MindInsight context.
  104. Args:
  105. workspace (str): specify mindinsight workspace, default is ''.
  106. config (str): specify mindinsight config file, default is ''.
  107. Raises:
  108. FileSystemPermissionError, if workspace is not allowed to access or available.
  109. """
  110. # set umask to 0o077
  111. os.umask(stat.S_IRWXG | stat.S_IRWXO)
  112. # assign argument values into environment
  113. if workspace:
  114. kwargs['workspace'] = workspace
  115. if config:
  116. kwargs['config'] = config
  117. for key, value in kwargs.items():
  118. variable = 'MINDINSIGHT_{}'.format(key.upper())
  119. os.environ[variable] = str(value)
  120. settings.refresh()
  121. if os.path.exists(settings.WORKSPACE):
  122. if not os.access(settings.WORKSPACE, os.R_OK | os.W_OK | os.X_OK):
  123. raise FileSystemPermissionError('Workspace {} not allowed to access'.format(workspace))
  124. else:
  125. try:
  126. os.makedirs(settings.WORKSPACE, mode=stat.S_IRWXU, exist_ok=True)
  127. except OSError:
  128. # race condition or priority problem
  129. raise FileSystemPermissionError('Workspace {} not available'.format(workspace))
  130. for hook in HookUtils.instance().hooks():
  131. hook.on_init()