]> git.ipfire.org Git - ddns.git/blob - src/ddns/__init__.py
Allow a missing [config] section.
[ddns.git] / src / ddns / __init__.py
1 #!/usr/bin/python
2 ###############################################################################
3 # #
4 # ddns - A dynamic DNS client for IPFire #
5 # Copyright (C) 2012 IPFire development team #
6 # #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
11 # #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
16 # #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
19 # #
20 ###############################################################################
21
22 import logging
23 import logging.handlers
24 import ConfigParser
25
26 from i18n import _
27
28 logger = logging.getLogger("ddns.core")
29 logger.propagate = 1
30
31 import providers
32
33 from .system import DDNSSystem
34
35 # Setup the logger.
36 def setup_logging():
37 rootlogger = logging.getLogger("ddns")
38 rootlogger.setLevel(logging.INFO)
39
40 # Setup a logger that logs to syslog.
41 handler = logging.handlers.SysLogHandler(address="/dev/log",
42 facility=logging.handlers.SysLogHandler.LOG_DAEMON
43 )
44 handler.setLevel(logging.INFO)
45 rootlogger.addHandler(handler)
46
47 handler = logging.StreamHandler()
48 rootlogger.addHandler(handler)
49
50 setup_logging()
51
52 class DDNSCore(object):
53 def __init__(self, debug=False):
54 # In debug mode, enable debug logging.
55 if debug:
56 rootlogger = logging.getLogger("ddns")
57 rootlogger.setLevel(logging.DEBUG)
58
59 logger.debug(_("Debugging mode enabled"))
60
61 # Initialize the settings array.
62 self.settings = {}
63
64 # Dict with all providers, that are supported.
65 self.providers = providers.get()
66
67 for handle, provider in sorted(self.providers.items()):
68 logger.debug("Registered new provider: %s (%s)" % (provider.name, provider.handle))
69
70 # List of configuration entries.
71 self.entries = []
72
73 # Add the system class.
74 self.system = DDNSSystem(self)
75
76 def get_provider_names(self):
77 """
78 Returns a list of names of all registered providers.
79 """
80 return sorted(self.providers.keys())
81
82 def load_configuration(self, filename):
83 logger.debug(_("Loading configuration file %s") % filename)
84
85 configs = ConfigParser.SafeConfigParser()
86 configs.read([filename,])
87
88 # First apply all global configuration settings.
89 try:
90 for k, v in configs.items("config"):
91 self.settings[k] = v
92
93 # Allow missing config section
94 except ConfigParser.NoSectionError:
95 pass
96
97 for entry in configs.sections():
98 # Skip the special config section.
99 if entry == "config":
100 continue
101
102 settings = {}
103 for k, v in configs.items(entry):
104 settings[k] = v
105 settings["hostname"] = entry
106
107 # Get the name of the provider.
108 provider = settings.get("provider", None)
109 if not provider:
110 logger.warning("Entry '%s' lacks a provider setting. Skipping." % entry)
111 continue
112
113 # Try to find the provider with the wanted name.
114 try:
115 provider = self.providers[provider]
116 except KeyError:
117 logger.warning("Could not find provider '%s' for entry '%s'." % (provider, entry))
118 continue
119
120 # Create an instance of the provider object with settings from the
121 # configuration file.
122 entry = provider(self, **settings)
123
124 # Add new entry to list (if not already exists).
125 if not entry in self.entries:
126 self.entries.append(entry)
127
128 def updateone(self, hostname, **kwargs):
129 for entry in self.entries:
130 if not entry.hostname == hostname:
131 continue
132
133 return self._update(entry, **kwargs)
134
135 raise DDNSHostNotFoundError(hostname)
136
137 def updateall(self, **kwargs):
138 """
139 Update all configured entries.
140 """
141 # If there are no entries, there is nothing to do.
142 if not self.entries:
143 logger.debug(_("Found no entries in the configuration file. Exiting."))
144 return
145
146 for entry in self.entries:
147 self._update(entry, **kwargs)
148
149 def _update(self, entry, force=False):
150 try:
151 entry(force=force)
152
153 except DDNSError, e:
154 logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) failed:") % \
155 { "hostname" : entry.hostname, "provider" : entry.name })
156 logger.error(" %s: %s" % (e.__class__.__name__, e.reason))
157 if e.message:
158 logger.error(" %s" % e.message)
159
160 except Exception, e:
161 logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) throwed an unhandled exception:") % \
162 { "hostname" : entry.hostname, "provider" : entry.name }, exc_info=True)
163
164 else:
165 logger.info(_("Dynamic DNS update for %(hostname)s (%(provider)s) successful") % \
166 { "hostname" : entry.hostname, "provider" : entry.name })