Debian Codegraph @

networking_bagpipe/bagpipe_bgp/common/utils.py

raw
1 # Copyright 2014 Orange
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 import collections
16 import re
17
18 from oslo_concurrency import lockutils
19 from oslo_config import cfg
20
21 from networking_bagpipe._i18n import _
22 from networking_bagpipe.bagpipe_bgp.engine import exa
23
24
25 def synchronized(method):
26
27 def synchronized_method(self, *arg, **kws):
28 with self.lock:
29 return method(self, *arg, **kws)
30
31 return synchronized_method
32
33
34 oslo_synchronized = lockutils.synchronized_with_prefix('bagpipe-bgp-')
35
36
37 def plural(x):
38 if len(x) > 1:
39 return "s"
40 else:
41 return ""
42
43
44 def invert_dict_of_sets(d):
45 '''return inverted dict of sets from original dict
46
47 original dict possibly containing sets of non-unique hashable items
48 '''
49 new_d = collections.defaultdict(set)
50 for k in d:
51 for v in d[k]:
52 new_d[v].add(k)
53 return new_d
54
55
56 camel2underscore_regex = re.compile('(?!^)([A-Z]+)')
57
58
59 def dict_camelcase_to_underscore(dictionary):
60 '''copy dict, with translation of keys from FooBar to foo_bar'''
61 return {camel2underscore_regex.sub(r'_\1', key).lower(): value
62 for (key, value) in dictionary.items()
63 }
64
65
66 def osloconfig_json_serialize(obj):
67 if (isinstance(obj, cfg.ConfigOpts) or
68 isinstance(obj, cfg.ConfigOpts.GroupAttr)):
69 return {osloconfig_json_serialize(k): osloconfig_json_serialize(v)
70 for k, v in obj.items()}
71 return obj
72
73
74 def convert_route_targets(orig_list):
75 assert isinstance(orig_list, list)
76 list_ = []
77 for rt in orig_list:
78 if rt == '':
79 continue
80 try:
81 asn, nn = rt.split(':')
82 list_.append(exa.RouteTarget(int(asn), int(nn)))
83 except Exception:
84 raise Exception(_("Malformed route target: '%s'" % rt))
85 return list_
86
87
88 class ClassReprMixin:
89
90 def __repr__(self):
91 return self.__class__.__name__