Open Kilda Java Documentation
common.py
Go to the documentation of this file.
1 # Copyright 2017 Telstra Open Source
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 
16 import collections
17 import signal
18 import weakref
19 
20 from kilda.traffexam import exc
21 
22 
23 class Resource(object):
24  _nesting_level = 0
25 
26  def __enter__(self):
27  if not self._nesting_level:
28  self.acquire()
29  self._nesting_level += 1
30  return self
31 
32  def __exit__(self, *exc_info):
33  self._nesting_level -= 1
34  if not self._nesting_level:
35  self.release()
36 
37  def acquire(self):
38  raise NotImplementedError
39 
40  def release(self):
41  raise NotImplementedError
42 
43 
44 class Registry(object):
45  def __init__(self):
46  self._data = {}
47 
48  def add(self, klass, value):
49  self._data[klass] = value
50 
51  def fetch(self, klass, remove=False):
52  try:
53  if remove:
54  value = self._data.pop(klass)
55  else:
56  value = self._data[klass]
57  except KeyError:
58  raise exc.RegistryLookupError(self, klass)
59  return value
60 
61 
62 class ProcMonitor(collections.Iterable):
63  def __init__(self):
64  self.proc_set = weakref.WeakSet()
65 
66  def __iter__(self):
67  return iter(self.proc_set)
68 
69  def add(self, proc):
70  self.proc_set.add(proc)
71 
72  def check_status(self):
73  for proc in self.proc_set:
74  proc.poll()
75 
76 
77 class AbstractSignal(object):
78  def __init__(self, signum):
79  self.signum = signum
80  self.replaced_handler = signal.signal(self.signum, self)
81 
82  def __call__(self, signum, frame):
83  self.handle()
84 
85  def handle(self):
86  raise NotImplementedError
def __call__(self, signum, frame)
Definition: common.py:82
def add(self, klass, value)
Definition: common.py:48
def __exit__(self, exc_info)
Definition: common.py:32
def fetch(self, klass, remove=False)
Definition: common.py:51