Initial commit
[ta/config-manager.git] / cmframework / src / cmframework / server / cmcsn.py
1 # Copyright 2019 Nokia
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 import logging
15 import copy
16 import json
17
18 from cmframework.apis import cmerror
19
20
21 class CMCSN(object):
22     CONFIG_NAME = 'cloud.cmframework'
23
24     def __init__(self, backend_handler):
25         self.backend_handler = backend_handler
26         self.config = {'csn': {'global': 0, 'nodes': {}}}
27         self._get_config()
28         logging.info('Current csn is %d', self.get())
29
30     def _update_csn(self, node_name=None):
31         new_config = copy.deepcopy(self.config)
32
33         if not node_name:
34             new_config['csn']['global'] += 1
35             logging.info('Updating csn to %d', new_config['csn']['global'])
36         else:
37             new_config['csn']['nodes'][node_name] = new_config['csn']['global']
38             logging.info('Updating csn for node %s to %s', node_name, new_config['csn']['global'])
39
40         self.backend_handler.set_property(CMCSN.CONFIG_NAME, json.dumps(new_config))
41         self.config = new_config
42
43     def _get_config(self):
44         try:
45             self.config = json.loads(self.backend_handler.get_property(CMCSN.CONFIG_NAME))
46         except cmerror.CMError as exp:
47             logging.info('Context id not defined')
48         except Exception as exp:  # pylint: disable=broad-except
49             logging.warning('Got error: %s', exp)
50
51     def increment(self):
52         self._update_csn()
53
54     def get(self):
55         return self.config['csn']['global']
56
57     def get_node_csn(self, node_name):
58         return self.config['csn']['nodes'].get(node_name, 1)
59
60     def sync_node_csn(self, node_name):
61         self._update_csn(node_name)