Initial commit
[ta/config-manager.git] / cmframework / src / cmframework / utils / cmflagfile.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 from __future__ import print_function
15 import logging
16 import os.path
17 import os
18 import stat
19
20 from cmframework.apis import cmerror
21
22
23 class CMFlagFile(object):
24     CM_FLAGFILE_DIR = '/mnt/config-manager'
25
26     def __init__(self, name):
27         logging.debug('CMFlagFile constructor called, name=%s', name)
28
29         self._name = '{}/{}'.format(CMFlagFile.CM_FLAGFILE_DIR, name)
30
31     def __nonzero__(self):
32         return self.is_set()
33
34     def is_set(self):
35         logging.debug('is_set called')
36
37         return os.path.exists(self._name)
38
39     def set(self):
40         logging.debug('set called')
41
42         if not self.is_set():
43             try:
44                 with open(self._name, 'w') as f:
45                     os.chmod(self._name, stat.S_IRUSR | stat.S_IWUSR)
46                     f.write('')
47                     f.flush()
48                     os.fsync(f.fileno())
49             except IOError as exp:
50                 raise cmerror.CMError(str(exp))
51
52     def unset(self):
53         logging.debug('unset called')
54
55         if self.is_set():
56             try:
57                 os.remove(self._name)
58             except IOError as exp:
59                 raise cmerror.CMError(str(exp))