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