]> git.ipfire.org Git - oddments/ddns.git/blob - src/ddns/__init__.py
4e4093e2690d731376f2a0ca2603be18f5bd03ac
[oddments/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 .errors import *
34 from .system import DDNSSystem
35
36 # Setup the logger.
37 def setup_logging():
38 rootlogger = logging.getLogger("ddns")
39 rootlogger.setLevel(logging.INFO)
40
41 # Setup a logger that logs to syslog.
42 handler = logging.handlers.SysLogHandler(address="/dev/log",
43 facility=logging.handlers.SysLogHandler.LOG_DAEMON
44 )
45 handler.setLevel(logging.INFO)
46 rootlogger.addHandler(handler)
47
48 handler = logging.StreamHandler()
49 rootlogger.addHandler(handler)
50
51 setup_logging()
52
53 class DDNSCore(object):
54 def __init__(self, debug=False):
55 # In debug mode, enable debug logging.
56 if debug:
57 rootlogger = logging.getLogger("ddns")
58 rootlogger.setLevel(logging.DEBUG)
59
60 logger.debug(_("Debugging mode enabled"))
61
62 # Initialize the settings array.
63 self.settings = {}
64
65 # Dict with all providers, that are supported.
66 self.providers = providers.get()
67
68 for handle, provider in sorted(self.providers.items()):
69 logger.debug("Registered new provider: %s (%s)" % (provider.name, provider.handle))
70
71 # List of configuration entries.
72 self.entries = []
73
74 # Add the system class.
75 self.system = DDNSSystem(self)
76
77 def get_provider_names(self):
78 """
79 Returns a list of names of all registered providers.
80 """
81 return sorted(self.providers.keys())
82
83 def load_configuration(self, filename):
84 logger.debug(_("Loading configuration file %s") % filename)
85
86 configs = ConfigParser.SafeConfigParser()
87 configs.read([filename,])
88
89 # First apply all global configuration settings.
90 try:
91 for k, v in configs.items("config"):
92 self.settings[k] = v
93
94 # Allow missing config section
95 except ConfigParser.NoSectionError:
96 pass
97
98 for entry in configs.sections():
99 # Skip the special config section.
100 if entry == "config":
101 continue
102
103 settings = {}
104 for k, v in configs.items(entry):
105 settings[k] = v
106 settings["hostname"] = entry
107
108 # Get the name of the provider.
109 provider = settings.get("provider", None)
110 if not provider:
111 logger.warning("Entry '%s' lacks a provider setting. Skipping." % entry)
112 continue
113
114 # Try to find the provider with the wanted name.
115 try:
116 provider = self.providers[provider]
117 except KeyError:
118 logger.warning("Could not find provider '%s' for entry '%s'." % (provider, entry))
119 continue
120
121 # Create an instance of the provider object with settings from the
122 # configuration file.
123 entry = provider(self, **settings)
124
125 # Add new entry to list (if not already exists).
126 if not entry in self.entries:
127 self.entries.append(entry)
128
129 def updateone(self, hostname, **kwargs):
130 for entry in self.entries:
131 if not entry.hostname == hostname:
132 continue
133
134 return self._update(entry, **kwargs)
135
136 raise DDNSHostNotFoundError(hostname)
137
138 def updateall(self, **kwargs):
139 """
140 Update all configured entries.
141 """
142 # If there are no entries, there is nothing to do.
143 if not self.entries:
144 logger.debug(_("Found no entries in the configuration file. Exiting."))
145 return
146
147 for entry in self.entries:
148 self._update(entry, **kwargs)
149
150 def _update(self, entry, force=False):
151 try:
152 entry(force=force)
153
154 except DDNSError, e:
155 logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) failed:") % \
156 { "hostname" : entry.hostname, "provider" : entry.name })
157 logger.error(" %s: %s" % (e.__class__.__name__, e.reason))
158 if e.message:
159 logger.error(" %s" % e.message)
160
161 except Exception, e:
162 logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) throwed an unhandled exception:") % \
163 { "hostname" : entry.hostname, "provider" : entry.name }, exc_info=True)
164
165 else:
166 logger.info(_("Dynamic DNS update for %(hostname)s (%(provider)s) successful") % \
167 { "hostname" : entry.hostname, "provider" : entry.name })