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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
16 from urlparse import urlparse
17 from configparser import ConfigParser
22 from cmframework.apis import cmerror
23 from cmframework.apis import cmstate
26 class CMStateFileHandler(cmstate.CMState):
27 def __init__(self, **kw):
28 uridata = urlparse(kw['uri'])
29 self.path = uridata.path
30 self.configparser = ConfigParser()
31 self._load_config_file()
33 def _load_config_file(self):
35 if os.path.isfile(self.path):
36 with open(self.path, 'r') as cf:
37 self.configparser.read_file(cf)
39 with open(self.path, 'w') as cf:
42 raise cmerror.CMError(str(ex))
44 def _write_config_file(self):
46 with open(self.path, 'w') as cf:
47 os.chmod(self.path, stat.S_IRUSR | stat.S_IWUSR)
48 self.configparser.write(cf)
50 raise cmerror.CMError(str(ex))
52 def get(self, domain, name):
53 logging.debug('get called for %s %s', domain, name)
55 if self.configparser.has_section(domain):
56 if self.configparser.has_option(domain, name):
57 return self.configparser.get(domain, name)
61 def get_domain(self, domain):
62 logging.debug('get_domain called for %s', domain)
64 if self.configparser.has_section(domain):
65 return self.configparser.items(domain)
69 def set(self, domain, name, value):
70 logging.debug('set called for setting %s %s=%s', domain, name, value)
72 if not self.configparser.has_section(domain):
73 self.configparser.add_section(domain)
75 self.configparser.set(domain, name, value)
77 self._write_config_file()
79 def get_domains(self):
80 logging.debug('get_domains called')
82 return self.configparser.sections()
84 def delete(self, domain, name):
85 logging.debug('delete called for %s %s', domain, name)
87 if self.configparser.has_section(domain):
88 self.configparser.remove_option(domain, name)
90 self._write_config_file()
92 def delete_domain(self, domain):
93 logging.debug('delete_domain called for %s', domain)
95 self.configparser.remove_section(domain)
97 self._write_config_file()