a764c2ce4804bb9b29c20fb436c79fe02526f51a
[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 from .providers import *
32 from .system import DDNSSystem
33
34 # Setup the logger.
35 def setup_logging():
36         rootlogger = logging.getLogger("ddns")
37         rootlogger.setLevel(logging.INFO)
38
39         # Setup a logger that logs to syslog.
40         handler = logging.handlers.SysLogHandler(address="/dev/log",
41                 facility=logging.handlers.SysLogHandler.LOG_DAEMON
42         )
43         handler.setLevel(logging.INFO)
44         rootlogger.addHandler(handler)
45
46         handler = logging.StreamHandler()
47         rootlogger.addHandler(handler)
48
49 setup_logging()
50
51 class DDNSCore(object):
52         def __init__(self, debug=False):
53                 # In debug mode, enable debug logging.
54                 if debug:
55                         logger.setLevel(logging.DEBUG)
56                         logger.debug(_("Debugging mode enabled"))
57
58                 # Initialize the settings array.
59                 self.settings = {}
60
61                 # Dict with all providers, that are supported.
62                 self.providers = {}
63                 self.register_all_providers()
64
65                 # List of configuration entries.
66                 self.entries = []
67
68                 # Add the system class.
69                 self.system = DDNSSystem(self)
70
71         def register_provider(self, provider):
72                 """
73                         Registers a new provider.
74                 """
75                 assert issubclass(provider, DDNSProvider)
76
77                 provider_handle = provider.INFO.get("handle")
78                 assert provider_handle
79
80                 assert not self.providers.has_key(provider_handle), \
81                         "Provider '%s' has already been registered" % provider_handle
82
83                 provider_name = provider.INFO.get("name")
84                 assert provider_name
85
86                 logger.debug("Registered new provider: %s (%s)" % (provider_name, provider_handle))
87                 self.providers[provider_handle] = provider
88
89         def register_all_providers(self):
90                 """
91                         Simply registers all providers.
92                 """
93                 for provider in (
94                         DDNSProviderAllInkl,
95                         DDNSProviderDHS,
96                         DDNSProviderDNSpark,
97                         DDNSProviderDtDNS,
98                         DDNSProviderDynDNS,
99                         DDNSProviderDynU,
100                         DDNSProviderEasyDNS,
101                         DDNSProviderFreeDNSAfraidOrg,
102                         DDNSProviderNamecheap,
103                         DDNSProviderNOIP,
104                         DDNSProviderLightningWireLabs,
105                         DDNSProviderOVH,
106                         DDNSProviderRegfish,
107                         DDNSProviderSelfhost,
108                         DDNSProviderSPDNS,
109                         DDNSProviderVariomedia,
110                 ):
111                         self.register_provider(provider)
112
113         def get_provider_names(self):
114                 """
115                         Returns a list of names of all registered providers.
116                 """
117                 return sorted(self.providers.keys())
118
119         def load_configuration(self, filename):
120                 logger.debug(_("Loading configuration file %s") % filename)
121
122                 configs = ConfigParser.SafeConfigParser()
123                 configs.read([filename,])
124
125                 # First apply all global configuration settings.
126                 for k, v in configs.items("config"):
127                         self.settings[k] = v
128
129                 for entry in configs.sections():
130                         # Skip the special config section.
131                         if entry == "config":
132                                 continue
133
134                         settings = {}
135                         for k, v in configs.items(entry):
136                                 settings[k] = v
137                         settings["hostname"] = entry
138
139                         # Get the name of the provider.
140                         provider = settings.get("provider", None)
141                         if not provider:
142                                 logger.warning("Entry '%s' lacks a provider setting. Skipping." % entry)
143                                 continue
144
145                         # Try to find the provider with the wanted name.
146                         try:
147                                 provider = self.providers[provider]
148                         except KeyError:
149                                 logger.warning("Could not find provider '%s' for entry '%s'." % (provider, entry))
150                                 continue
151
152                         # Create an instance of the provider object with settings from the
153                         # configuration file.
154                         entry = provider(self, **settings)
155
156                         # Add new entry to list (if not already exists).
157                         if not entry in self.entries:
158                                 self.entries.append(entry)
159
160         def updateone(self, hostname, **kwargs):
161                 for entry in self.entries:
162                         if not entry.hostname == hostname:
163                                 continue
164
165                         return self._update(entry, **kwargs)
166
167                 raise DDNSHostNotFoundError(hostname)
168
169         def updateall(self, **kwargs):
170                 """
171                         Update all configured entries.
172                 """
173                 # If there are no entries, there is nothing to do.
174                 if not self.entries:
175                         logger.debug(_("Found no entries in the configuration file. Exiting."))
176                         return
177
178                 for entry in self.entries:
179                         self._update(entry, **kwargs)
180
181         def _update(self, entry, force=False):
182                 try:
183                         entry(force=force)
184
185                 except DDNSUpdateError, e:
186                         logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) failed:") % \
187                                 { "hostname" : entry.hostname, "provider" : entry.name })
188                         logger.error("  %s" % e)
189
190                 except Exception, e:
191                         logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) throwed an unhandled exception:") % \
192                                 { "hostname" : entry.hostname, "provider" : entry.name })
193                         logger.error("  %s" % e)
194
195                 else:
196                         logger.info(_("Dynamic DNS update for %(hostname)s (%(provider)s) successful") % \
197                                 { "hostname" : entry.hostname, "provider" : entry.name })