]> git.ipfire.org Git - oddments/ddns.git/blame - src/ddns/database.py
ddns: Port to python3
[oddments/ddns.git] / src / ddns / database.py
CommitLineData
91aead36 1#!/usr/bin/python3
37e24fbf
MT
2###############################################################################
3# #
4# ddns - A dynamic DNS client for IPFire #
5# Copyright (C) 2014 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
22import datetime
63e16fee 23import os
37e24fbf
MT
24import sqlite3
25
26# Initialize the logger.
27import logging
28logger = logging.getLogger("ddns.database")
29logger.propagate = 1
30
31class DDNSDatabase(object):
32 def __init__(self, core, path):
33 self.core = core
63e16fee 34 self.path = path
37e24fbf 35
63e16fee
MT
36 # We won't open the connection to the database directly
37 # so that we do not do it unnecessarily.
38 self._db = None
37e24fbf
MT
39
40 def __del__(self):
41 self._close_database()
42
43 def _open_database(self, path):
44 logger.debug("Opening database %s" % path)
45
46 exists = os.path.exists(path)
47
48 conn = sqlite3.connect(path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
49 conn.isolation_level = None
50
63e16fee 51 if not exists and self.is_writable():
37e24fbf
MT
52 logger.debug("Initialising database layout")
53 c = conn.cursor()
54 c.executescript("""
55 CREATE TABLE updates (
56 hostname TEXT NOT NULL,
57 status TEXT NOT NULL,
58 message TEXT,
59 timestamp timestamp NOT NULL
60 );
61
62 CREATE TABLE settings (
63 k TEXT NOT NULL,
64 v TEXT NOT NULL
65 );
a2857a13
MT
66
67 CREATE INDEX idx_updates_hostname ON updates(hostname);
37e24fbf
MT
68 """)
69 c.execute("INSERT INTO settings(k, v) VALUES(?, ?)", ("version", "1"))
70
71 return conn
72
63e16fee
MT
73 def is_writable(self):
74 # Check if the database file exists and is writable.
75 ret = os.access(self.path, os.W_OK)
76 if ret:
77 return True
78
79 # If not, we check if we are able to write to the directory.
80 # In that case the database file will be created in _open_database().
81 return os.access(os.path.dirname(self.path), os.W_OK)
82
37e24fbf
MT
83 def _close_database(self):
84 if self._db:
91aead36 85 # TODO: Check Unresolved attribute reference '_db_close' for class 'DDNSDatabase'
37e24fbf
MT
86 self._db_close()
87 self._db = None
88
89 def _execute(self, query, *parameters):
63e16fee
MT
90 if self._db is None:
91 self._db = self._open_database(self.path)
92
37e24fbf
MT
93 c = self._db.cursor()
94 try:
95 c.execute(query, parameters)
96 finally:
97 c.close()
98
99 def add_update(self, hostname, status, message=None):
63e16fee
MT
100 if not self.is_writable():
101 logger.warning("Could not log any updates because the database is not writable")
102 return
103
37e24fbf
MT
104 self._execute("INSERT INTO updates(hostname, status, message, timestamp) \
105 VALUES(?, ?, ?, ?)", hostname, status, message, datetime.datetime.utcnow())
106
107 def log_success(self, hostname):
108 logger.debug("Logging successful update for %s" % hostname)
109
110 return self.add_update(hostname, "success")
111
112 def log_failure(self, hostname, exception):
113 if exception:
114 message = "%s: %s" % (exception.__class__.__name__, exception.reason)
115 else:
116 message = None
117
118 logger.debug("Logging failed update for %s: %s" % (hostname, message or ""))
119
120 return self.add_update(hostname, "failure", message=message)
121
112d3fb8
MT
122 def last_update(self, hostname, status=None):
123 """
124 Returns the timestamp of the last update (with the given status code).
125 """
f62fa5ba
MT
126 if self._db is None:
127 self._db = self._open_database(self.path)
128
37e24fbf
MT
129 c = self._db.cursor()
130
131 try:
112d3fb8
MT
132 if status:
133 c.execute("SELECT timestamp FROM updates WHERE hostname = ? AND status = ? \
134 ORDER BY timestamp DESC LIMIT 1", (hostname, status))
135 else:
136 c.execute("SELECT timestamp FROM updates WHERE hostname = ? \
137 ORDER BY timestamp DESC LIMIT 1", (hostname,))
138
139 for row in c:
140 return row[0]
141 finally:
142 c.close()
143
144 def last_update_status(self, hostname):
145 """
146 Returns the update status of the last update.
147 """
f62fa5ba
MT
148 if self._db is None:
149 self._db = self._open_database(self.path)
150
112d3fb8
MT
151 c = self._db.cursor()
152
153 try:
154 c.execute("SELECT status FROM updates WHERE hostname = ? \
155 ORDER BY timestamp DESC LIMIT 1", (hostname,))
156
157 for row in c:
158 return row[0]
159 finally:
160 c.close()
161
162 def last_update_failure_message(self, hostname):
163 """
164 Returns the reason string for the last failed update (if any).
165 """
f62fa5ba
MT
166 if self._db is None:
167 self._db = self._open_database(self.path)
168
112d3fb8
MT
169 c = self._db.cursor()
170
171 try:
172 c.execute("SELECT message FROM updates WHERE hostname = ? AND status = ? \
173 ORDER BY timestamp DESC LIMIT 1", (hostname, "failure"))
37e24fbf
MT
174
175 for row in c:
176 return row[0]
177 finally:
178 c.close()