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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 threading
  18. from importlib import import_module
  19. from mindinsight.conf import settings
  20. from mindinsight.utils.exceptions import FileSystemPermissionError
  21. class BaseHook:
  22. """Base hook class."""
  23. def register_secure_domains(self):
  24. """Hook function to register secure domains."""
  25. return []
  26. def register_startup_arguments(self, parser):
  27. """
  28. Hook function to register startup arguments.
  29. Args:
  30. parser (ArgumentParser): specify parser to which arguments are added.
  31. """
  32. def on_startup(self, logger):
  33. """
  34. Hook function to on startup.
  35. Args:
  36. logger (Logger): script logger of start command.
  37. """
  38. def on_shutdown(self, logger):
  39. """
  40. Hook function to on shutdown.
  41. Args:
  42. logger (Logger): script logger of stop command.
  43. """
  44. def on_init(self):
  45. """Hook function to on init."""
  46. class HookUtils:
  47. """
  48. Lock utilities.
  49. Examples:
  50. >>> from mindinsight.utils.hook import HookUtils
  51. >>> for hook in HookUtils.instance().hooks():
  52. >>> domains = hook.register_secure_domains()
  53. >>> hook.register_startup_arguments(parser)
  54. >>> hook.on_startup(logger)
  55. >>> hook.on_shutdown(logger)
  56. >>> hook.on_init()
  57. """
  58. _lock = threading.Lock()
  59. _instance = None
  60. def __new__(cls, *args, **kwargs):
  61. """Built-in __new__ function."""
  62. if cls._instance is None:
  63. with cls._lock:
  64. if cls._instance is None:
  65. cls._instance = super().__new__(cls, *args, **kwargs)
  66. cls._instance.discover()
  67. return cls._instance
  68. def discover(self):
  69. """Discover hook instances."""
  70. self.__hooks = []
  71. mindinsight_path = os.path.join(__file__, os.pardir, os.pardir)
  72. hook_path = os.path.realpath(os.path.join(mindinsight_path, 'common/hook'))
  73. files = os.listdir(hook_path)
  74. files.sort()
  75. for file in files:
  76. if file.startswith('_') or not file.endswith('.py'):
  77. continue
  78. hook_name = file[:-len('.py')]
  79. hook_module = import_module('mindinsight.common.hook.{}'.format(hook_name))
  80. hook_cls = getattr(hook_module, 'Hook', None)
  81. if hook_cls is not None and issubclass(hook_cls, BaseHook):
  82. self.__hooks.append(hook_cls())
  83. def hooks(self):
  84. """
  85. Return list of hook instances.
  86. Returns:
  87. list, list of hook instances.
  88. """
  89. return self.__hooks
  90. @classmethod
  91. def instance(cls):
  92. """
  93. Produce singleton instance of HookUtils.
  94. Returns:
  95. HookUtils, singleton instance of HookUtils.
  96. """
  97. if cls._instance is None:
  98. cls._instance = cls()
  99. return cls._instance
  100. def init(workspace='', config='', **kwargs):
  101. """
  102. Init MindInsight context.
  103. Args:
  104. workspace (str): specify mindinsight workspace, default is ''.
  105. config (str): specify mindinsight config file, default is ''.
  106. Raises:
  107. FileSystemPermissionError, if workspace is not allowed to access or available.
  108. """
  109. permissions = os.R_OK | os.W_OK | os.X_OK
  110. # set umask to 0o077
  111. os.umask(permissions << 3 | permissions)
  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, permissions):
  123. raise FileSystemPermissionError('Workspace {} not allowed to access'.format(workspace))
  124. else:
  125. try:
  126. mode = permissions << 6
  127. os.makedirs(settings.WORKSPACE, mode=mode, exist_ok=True)
  128. except OSError:
  129. # race condition or priority problem
  130. raise FileSystemPermissionError('Workspace {} not available'.format(workspace))
  131. for hook in HookUtils.instance().hooks():
  132. hook.on_init()