blob: 3ba21a6fe525ffeb957b01df7134d4f17f084920 [file] [log] [blame]
Dave Pigott281203e2014-09-17 23:45:02 +01001#! /usr/bin/python
2
Steve McIntyrec03d68d2016-03-24 17:38:34 +00003# Copyright 2014-2016 Linaro Limited
Steve McIntyrec4890132015-08-07 15:19:11 +01004# Authors: Dave Pigott <dave.pigott@linaro.org>,
5# Steve McIntyre <steve.mcintyre@linaro.org>
Dave Pigott281203e2014-09-17 23:45:02 +01006#
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 2 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, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20# MA 02110-1301, USA.
21
22import psycopg2
23import psycopg2.extras
Steve McIntyre6a618162014-12-10 16:47:07 +000024import datetime, os, sys
Steve McIntyre7cf80982015-02-12 07:03:40 +000025import logging
Steve McIntyre6a618162014-12-10 16:47:07 +000026
Steve McIntyrec4890132015-08-07 15:19:11 +010027TRUNK_ID_NONE = -1
28
Steve McIntyre6a618162014-12-10 16:47:07 +000029if __name__ == '__main__':
30 vlandpath = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
31 sys.path.insert(0, vlandpath)
32 sys.path.insert(0, "%s/.." % vlandpath)
33
Steve McIntyreb01959f2016-03-22 17:02:39 +000034from errors import CriticalError, InputError, NotFoundError
Dave Pigott281203e2014-09-17 23:45:02 +010035
36class VlanDB:
Steve McIntyreea343aa2015-10-23 17:46:17 +010037 def __init__(self, db_name="vland", username="vland", readonly=True):
Dave Pigott281203e2014-09-17 23:45:02 +010038 try:
Steve McIntyree38f6222014-11-27 15:09:49 +000039 self.connection = psycopg2.connect(database=db_name, user=username)
Steve McIntyreb09ed282014-12-02 17:59:35 +000040 self.cursor = self.connection.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
Steve McIntyreea343aa2015-10-23 17:46:17 +010041 if not readonly:
42 self._init_state()
Dave Pigott281203e2014-09-17 23:45:02 +010043 except Exception as e:
Steve McIntyre5fa22652015-04-01 18:01:45 +010044 logging.error("Failed to access database: %s", e)
Steve McIntyre7cf80982015-02-12 07:03:40 +000045 raise
Dave Pigott281203e2014-09-17 23:45:02 +010046
47 def __del__(self):
48 self.cursor.close()
49 self.connection.close()
50
Steve McIntyreea343aa2015-10-23 17:46:17 +010051 # Create the state table (if needed) and add its only record
52 def _init_state(self):
53 try:
54 sql = "SELECT * FROM state"
55 self.cursor.execute(sql)
56 self.cursor.execute('DELETE FROM state')
57 except psycopg2.ProgrammingError:
58 self.connection.commit() # state doesn't exist; clear error
59 sql = "CREATE TABLE state (last_modified TIMESTAMP)"
60 self.cursor.execute(sql)
61 sql = "INSERT INTO state (last_modified) VALUES (%s)"
62 data = (datetime.datetime.now(), )
63 self.cursor.execute(sql, data)
64 self.connection.commit()
65
Steve McIntyre31d6dfa2014-12-02 12:35:56 +000066 # Create a new switch in the database. Switches are really simple
67 # devices - they're just containers for ports.
68 #
69 # Constraints:
70 # Switches must be uniquely named
Steve McIntyredbd7fe52014-11-27 16:54:29 +000071 def create_switch(self, name):
Steve McIntyre31d6dfa2014-12-02 12:35:56 +000072
Steve McIntyre549435f2014-12-05 15:42:46 +000073 switch_id = self.get_switch_id_by_name(name)
Steve McIntyre31d6dfa2014-12-02 12:35:56 +000074 if switch_id is not None:
75 raise InputError("Switch name %s already exists" % name)
76
Dave Pigott2649a1a2014-09-18 00:04:49 +010077 try:
Steve McIntyredbd7fe52014-11-27 16:54:29 +000078 sql = "INSERT INTO switch (name) VALUES (%s) RETURNING switch_id"
Steve McIntyre31d6dfa2014-12-02 12:35:56 +000079 data = (name, )
Steve McIntyredbd7fe52014-11-27 16:54:29 +000080 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +010081 switch_id = self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +010082 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Dave Pigott2649a1a2014-09-18 00:04:49 +010083 self.connection.commit()
84 except:
85 self.connection.rollback()
86 raise
Steve McIntyree1febdb2014-12-02 12:39:14 +000087
Dave Pigott281203e2014-09-17 23:45:02 +010088 return switch_id
89
Steve McIntyrec4890132015-08-07 15:19:11 +010090 # Create a new port in the database. Three of the fields are
91 # created with default values (is_locked, is_trunk, trunk_id)
92 # here, and should be updated separately if desired. For the
93 # current_vlan_id and base_vlan_id fields, *BE CAREFUL* that you
94 # have already looked up the correct VLAN_ID for each. This is
95 # *NOT* the same as the VLAN tag (likely to be 1). You Have Been
96 # Warned!
Steve McIntyrecb42ebf2014-12-02 12:36:45 +000097 #
98 # Constraints:
99 # 1. The switch referred to must already exist
100 # 2. The VLANs mentioned here must already exist
Steve McIntyre6a7fdb22014-12-05 15:17:30 +0000101 # 3. (Switch/name) must be unique
Steve McIntyreea753972015-08-05 13:52:48 +0100102 # 4. (Switch/number) must be unique
103 def create_port(self, switch_id, name, number, current_vlan_id, base_vlan_id):
Steve McIntyrecb42ebf2014-12-02 12:36:45 +0000104
Steve McIntyre549435f2014-12-05 15:42:46 +0000105 switch = self.get_switch_by_id(switch_id)
Steve McIntyrecb42ebf2014-12-02 12:36:45 +0000106 if switch is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000107 raise NotFoundError("Switch ID %d does not exist" % int(switch_id))
Steve McIntyrecb42ebf2014-12-02 12:36:45 +0000108
109 for vlan_id in (current_vlan_id, base_vlan_id):
Steve McIntyre549435f2014-12-05 15:42:46 +0000110 vlan = self.get_vlan_by_id(vlan_id)
Steve McIntyrecb42ebf2014-12-02 12:36:45 +0000111 if vlan is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000112 raise NotFoundError("VLAN ID %d does not exist" % int(vlan_id))
Steve McIntyre6a7fdb22014-12-05 15:17:30 +0000113
114 port_id = self.get_port_by_switch_and_name(switch_id, name)
115 if port_id is not None:
Steve McIntyrea1c75222014-12-05 16:57:13 +0000116 raise InputError("Already have a port %s on switch ID %d" % (name, int(switch_id)))
Steve McIntyre6a7fdb22014-12-05 15:17:30 +0000117
Steve McIntyreea753972015-08-05 13:52:48 +0100118 port_id = self.get_port_by_switch_and_number(switch_id, int(number))
119 if port_id is not None:
120 raise InputError("Already have a port %d on switch ID %d" % (int(number), int(switch_id)))
121
Dave Pigott2649a1a2014-09-18 00:04:49 +0100122 try:
Steve McIntyrec4890132015-08-07 15:19:11 +0100123 sql = "INSERT INTO port (name, number, switch_id, is_locked, is_trunk, current_vlan_id, base_vlan_id, trunk_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) RETURNING port_id"
Steve McIntyreea753972015-08-05 13:52:48 +0100124 data = (name, number, switch_id,
Steve McIntyre90a4a972014-11-28 16:50:56 +0000125 False, False,
Steve McIntyrec4890132015-08-07 15:19:11 +0100126 current_vlan_id, base_vlan_id, TRUNK_ID_NONE)
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000127 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +0100128 port_id = self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +0100129 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Dave Pigott2649a1a2014-09-18 00:04:49 +0100130 self.connection.commit()
131 except:
132 self.connection.rollback()
133 raise
Steve McIntyree1febdb2014-12-02 12:39:14 +0000134
Dave Pigott281203e2014-09-17 23:45:02 +0100135 return port_id
136
Steve McIntyreb005a2f2014-11-28 18:23:05 +0000137 # Create a new vlan in the database. We locally add a creation
138 # timestamp, for debug purposes. If vlans seems to be sticking
139 # around, we'll be able to see when they were created.
Steve McIntyre31b2df52014-12-02 12:37:54 +0000140 #
141 # Constraints:
142 # Names and tags must be unique
Steve McIntyre57f45912014-12-08 14:43:00 +0000143 # Tags must be in the range 1-4095 (802.1q spec)
Steve McIntyre49777e72014-12-08 16:00:46 +0000144 # Names can be any free-form text, length 1-32 characters
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000145 def create_vlan(self, name, tag, is_base_vlan):
Steve McIntyre31b2df52014-12-02 12:37:54 +0000146
Steve McIntyre57f45912014-12-08 14:43:00 +0000147 if int(tag) < 1 or int(tag) > 4095:
Steve McIntyre49777e72014-12-08 16:00:46 +0000148 raise InputError("VLAN tag %d is outside of the valid range (1-4095)" % int(tag))
149
150 if (len(name) < 1) or (len(name) > 32):
151 raise InputError("VLAN name %s is invalid (must be 1-32 chars)" % name)
Steve McIntyre57f45912014-12-08 14:43:00 +0000152
Steve McIntyrea34c1812014-12-05 15:27:55 +0000153 vlan_id = self.get_vlan_id_by_name(name)
Steve McIntyre31b2df52014-12-02 12:37:54 +0000154 if vlan_id is not None:
155 raise InputError("VLAN name %s is already in use" % name)
156
Steve McIntyre50eb0602014-12-05 15:29:04 +0000157 vlan_id = self.get_vlan_id_by_tag(tag)
Steve McIntyre31b2df52014-12-02 12:37:54 +0000158 if vlan_id is not None:
159 raise InputError("VLAN tag %d is already in use" % int(tag))
160
Dave Pigott2649a1a2014-09-18 00:04:49 +0100161 try:
Steve McIntyred74d97c2014-11-28 14:44:39 +0000162 dt = datetime.datetime.now()
Steve McIntyre4b918132014-12-05 17:04:46 +0000163 sql = "INSERT INTO vlan (name, tag, is_base_vlan, creation_time) VALUES (%s, %s, %s, %s) RETURNING vlan_id"
164 data = (name, tag, is_base_vlan, dt)
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000165 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +0100166 vlan_id = self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +0100167 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Dave Pigott2649a1a2014-09-18 00:04:49 +0100168 self.connection.commit()
169 except:
170 self.connection.rollback()
171 raise
Steve McIntyree1febdb2014-12-02 12:39:14 +0000172
Dave Pigott281203e2014-09-17 23:45:02 +0100173 return vlan_id
174
Steve McIntyrec4890132015-08-07 15:19:11 +0100175 # Create a new trunk in the database, linking two ports. Trunks
176 # are really simple objects for our use - they're just containers
177 # for 2 ports.
178 #
179 # Constraints:
180 # 1. Both ports listed must already exist.
181 # 2. Both ports must be in trunk mode.
182 # 3. Both must not be locked.
183 # 4. Both must not already be in a trunk.
184 def create_trunk(self, port_id1, port_id2):
185
186 for port_id in (port_id1, port_id2):
187 port = self.get_port_by_id(int(port_id))
188 if port is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000189 raise NotFoundError("Port ID %d does not exist" % int(port_id))
Steve McIntyrec4890132015-08-07 15:19:11 +0100190 if not port.is_trunk:
191 raise InputError("Port ID %d is not in trunk mode" % int(port_id))
192 if port.is_locked:
193 raise InputError("Port ID %d is locked" % int(port_id))
194 if port.trunk_id != TRUNK_ID_NONE:
195 raise InputError("Port ID %d is already on trunk ID %d" % (int(port_id), int(port.trunk_id)))
196
197 try:
198 # Add the trunk itself
199 dt = datetime.datetime.now()
200 sql = "INSERT INTO trunk (creation_time) VALUES (%s) RETURNING trunk_id"
201 data = (dt, )
202 self.cursor.execute(sql, data)
203 trunk_id = self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +0100204 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Steve McIntyrec4890132015-08-07 15:19:11 +0100205 self.connection.commit()
206 # And update the ports
207 for port_id in (port_id1, port_id2):
208 self._set_port_trunk(port_id, trunk_id)
209 except:
210 self.delete_trunk(trunk_id)
211 raise
212
213 return trunk_id
214
Steve McIntyre2d685c72014-12-08 15:24:12 +0000215 # Internal helper function
Dave Pigott281203e2014-09-17 23:45:02 +0100216 def _delete_row(self, table, field, value):
Dave Pigott2649a1a2014-09-18 00:04:49 +0100217 try:
Steve McIntyree03de002014-12-02 17:14:14 +0000218 sql = "DELETE FROM %s WHERE %s = %s" % (table, field, '%s')
219 data = (value,)
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000220 self.cursor.execute(sql, data)
Steve McIntyreea343aa2015-10-23 17:46:17 +0100221 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Dave Pigott2649a1a2014-09-18 00:04:49 +0100222 self.connection.commit()
223 except:
224 self.connection.rollback()
225 raise
Dave Pigott281203e2014-09-17 23:45:02 +0100226
Steve McIntyre388f0e22014-12-02 17:19:04 +0000227 # Delete the specified switch
228 #
229 # Constraints:
230 # 1. The switch must exist
231 # 2. The switch may not be referenced by any ports -
232 # delete them first!
Dave Pigott281203e2014-09-17 23:45:02 +0100233 def delete_switch(self, switch_id):
Steve McIntyre549435f2014-12-05 15:42:46 +0000234 switch = self.get_switch_by_id(switch_id)
Steve McIntyre388f0e22014-12-02 17:19:04 +0000235 if switch is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000236 raise NotFoundError("Switch ID %d does not exist" % int(switch_id))
Steve McIntyre388f0e22014-12-02 17:19:04 +0000237 ports = self.get_ports_by_switch(switch_id)
238 if ports is not None:
Steve McIntyrea1c75222014-12-05 16:57:13 +0000239 raise InputError("Cannot delete switch ID %d when it still has %d ports" %
240 (int(switch_id), len(ports)))
Dave Pigott281203e2014-09-17 23:45:02 +0100241 self._delete_row("switch", "switch_id", switch_id)
Steve McIntyre388f0e22014-12-02 17:19:04 +0000242 return switch_id
Dave Pigott281203e2014-09-17 23:45:02 +0100243
Steve McIntyre6a968622014-12-02 18:01:41 +0000244 # Delete the specified port
245 #
246 # Constraints:
247 # 1. The port must exist
248 # 2. The port must not be locked
Dave Pigott281203e2014-09-17 23:45:02 +0100249 def delete_port(self, port_id):
Steve McIntyre549435f2014-12-05 15:42:46 +0000250 port = self.get_port_by_id(port_id)
Steve McIntyre6a968622014-12-02 18:01:41 +0000251 if port is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000252 raise NotFoundError("Port ID %d does not exist" % int(port_id))
Steve McIntyre6a968622014-12-02 18:01:41 +0000253 if port.is_locked:
Steve McIntyrea1c75222014-12-05 16:57:13 +0000254 raise InputError("Cannot delete port ID %d as it is locked" % int(port_id))
Dave Pigott281203e2014-09-17 23:45:02 +0100255 self._delete_row("port", "port_id", port_id)
Steve McIntyre6a968622014-12-02 18:01:41 +0000256 return port_id
Dave Pigott281203e2014-09-17 23:45:02 +0100257
Steve McIntyre14552ac2014-12-05 15:23:57 +0000258 # Delete the specified VLAN
259 #
260 # Constraints:
Steve McIntyre2a5df972015-08-07 15:19:40 +0100261 # 1. The VLAN must exist
Steve McIntyre14552ac2014-12-05 15:23:57 +0000262 # 2. The VLAN may not contain any ports - move or delete them first!
Dave Pigott281203e2014-09-17 23:45:02 +0100263 def delete_vlan(self, vlan_id):
Steve McIntyre549435f2014-12-05 15:42:46 +0000264 vlan = self.get_vlan_by_id(vlan_id)
Steve McIntyre14552ac2014-12-05 15:23:57 +0000265 if vlan is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000266 raise NotFoundError("VLAN ID %d does not exist" % int(vlan_id))
Steve McIntyre14552ac2014-12-05 15:23:57 +0000267 ports = self.get_ports_by_current_vlan(vlan_id)
268 if ports is not None:
Steve McIntyrea1c75222014-12-05 16:57:13 +0000269 raise InputError("Cannot delete VLAN ID %d when it still has %d ports" %
270 (int(vlan_id), len(ports)))
Steve McIntyre14552ac2014-12-05 15:23:57 +0000271 ports = self.get_ports_by_base_vlan(vlan_id)
272 if ports is not None:
Steve McIntyrea1c75222014-12-05 16:57:13 +0000273 raise InputError("Cannot delete VLAN ID %d when it still has %d ports" %
274 (int(vlan_id), len(ports)))
Dave Pigott281203e2014-09-17 23:45:02 +0100275 self._delete_row("vlan", "vlan_id", vlan_id)
Steve McIntyre14552ac2014-12-05 15:23:57 +0000276 return vlan_id
Dave Pigott281203e2014-09-17 23:45:02 +0100277
Steve McIntyrec4890132015-08-07 15:19:11 +0100278 # Delete the specified trunk
279 #
280 # Constraints:
281 # 1. The trunk must exist
282 #
283 # Any ports attached will be detached (i.e. moved to trunk TRUNK_ID_NONE)
284 def delete_trunk(self, trunk_id):
285 trunk = self.get_trunk_by_id(trunk_id)
286 if trunk is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000287 raise NotFoundError("Trunk ID %d does not exist" % int(trunk_id))
Steve McIntyrec4890132015-08-07 15:19:11 +0100288 ports = self.get_ports_by_trunk(trunk_id)
289 for port_id in ports:
290 self._set_port_trunk(port_id, TRUNK_ID_NONE)
291 self._delete_row("trunk", "trunk_id", trunk_id)
292 return trunk_id
293
Steve McIntyre6c4f33f2015-08-03 19:25:07 +0100294 # Find the lowest unused VLAN tag and return it
295 #
296 # Constraints:
297 # None
298 def find_lowest_unused_vlan_tag(self):
299 sql = "SELECT tag FROM vlan ORDER BY tag ASC"
300 self.cursor.execute(sql,)
301
302 # Walk through the list, looking for gaps
303 last = 1
304 result = None
305
306 for record in self.cursor:
307 if (record[0] - last) > 1:
308 result = last + 1
309 break
310 last = record[0]
311
312 if result is None:
313 result = last + 1
314
315 if result > 4093:
316 raise CriticalError("Can't find any VLAN tags remaining for allocation!")
317
318 return result
319
Steve McIntyre2d685c72014-12-08 15:24:12 +0000320 # Grab one column from one row of a query on one column; useful as
321 # a quick wrapper
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100322 def _get_element(self, select_field, table, compare_field, value):
Steve McIntyre95614c22014-11-28 17:02:44 +0000323
324 # We really want to use psycopg's type handling deal with the
325 # (potentially) user-supplied data in the value field, so we
326 # have to pass (sql,data) through to cursor.execute. However,
327 # we can't have psycopg do all the argument substitution here
328 # as it will quote all the params like the table name. That
329 # doesn't work. So, we substitute a "%s" for "%s" here so we
330 # keep it after python's own string substitution.
331 sql = "SELECT %s FROM %s WHERE %s = %s" % (select_field, table, compare_field, "%s")
332
333 # Now, the next icky thing: we need to make sure that we're
334 # passing a dict so that psycopg2 can pick it apart properly
335 # for its own substitution code. We force this with the
336 # trailing comma here
337 data = (value, )
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000338 self.cursor.execute(sql, data)
Steve McIntyre95614c22014-11-28 17:02:44 +0000339
Steve McIntyre58b57a42014-12-02 13:09:21 +0000340 if self.cursor.rowcount > 0:
341 return self.cursor.fetchone()[0]
342 else:
Steve McIntyrec831f9c2014-12-02 12:38:54 +0000343 return None
Dave Pigott281203e2014-09-17 23:45:02 +0100344
Steve McIntyre2d685c72014-12-08 15:24:12 +0000345 # Grab one column from one row of a query on 2 columns; useful as
346 # a quick wrapper
Steve McIntyrea74c7fe2014-12-02 18:49:38 +0000347 def _get_element2(self, select_field, table, compare_field1, value1, compare_field2, value2):
348
349 # We really want to use psycopg's type handling deal with the
350 # (potentially) user-supplied data in the value field, so we
351 # have to pass (sql,data) through to cursor.execute. However,
352 # we can't have psycopg do all the argument substitution here
353 # as it will quote all the params like the table name. That
354 # doesn't work. So, we substitute a "%s" for "%s" here so we
355 # keep it after python's own string substitution.
356 sql = "SELECT %s FROM %s WHERE %s = %s AND %s = %s" % (select_field, table, compare_field1, "%s", compare_field2, "%s")
357
Steve McIntyrea74c7fe2014-12-02 18:49:38 +0000358 data = (value1, value2)
359 self.cursor.execute(sql, data)
360
361 if self.cursor.rowcount > 0:
362 return self.cursor.fetchone()[0]
363 else:
364 return None
365
Steve McIntyre2d685c72014-12-08 15:24:12 +0000366 # Grab one column from multiple rows of a query; useful as a quick
367 # wrapper
Steve McIntyre05e3e622015-09-25 01:29:18 +0100368 def _get_multi_elements(self, select_field, table, compare_field, value, sort_field):
Steve McIntyree9da15e2014-12-05 15:22:41 +0000369
370 # We really want to use psycopg's type handling deal with the
371 # (potentially) user-supplied data in the value field, so we
372 # have to pass (sql,data) through to cursor.execute. However,
373 # we can't have psycopg do all the argument substitution here
374 # as it will quote all the params like the table name. That
375 # doesn't work. So, we substitute a "%s" for "%s" here so we
376 # keep it after python's own string substitution.
Steve McIntyre05e3e622015-09-25 01:29:18 +0100377 sql = "SELECT %s FROM %s WHERE %s = %s ORDER BY %s ASC" % (select_field, table, compare_field, "%s", sort_field)
Steve McIntyree9da15e2014-12-05 15:22:41 +0000378
379 # Now, the next icky thing: we need to make sure that we're
380 # passing a dict so that psycopg2 can pick it apart properly
381 # for its own substitution code. We force this with the
382 # trailing comma here
383 data = (value, )
384 self.cursor.execute(sql, data)
385
386 if self.cursor.rowcount > 0:
387 results = []
388 for record in self.cursor:
Steve McIntyre52509622014-12-02 17:13:15 +0000389 results.append(record[0])
Steve McIntyree9da15e2014-12-05 15:22:41 +0000390 return results
Steve McIntyre52509622014-12-02 17:13:15 +0000391 else:
392 return None
393
Steve McIntyre7201c9b2014-12-17 17:33:51 +0000394 # Grab one column from multiple rows of a 2-part query; useful as
395 # a wrapper
Steve McIntyre05e3e622015-09-25 01:29:18 +0100396 def _get_multi_elements2(self, select_field, table, compare_field1, value1, compare_field2, value2, sort_field):
Steve McIntyre7201c9b2014-12-17 17:33:51 +0000397
398 # We really want to use psycopg's type handling deal with the
399 # (potentially) user-supplied data in the value field, so we
400 # have to pass (sql,data) through to cursor.execute. However,
401 # we can't have psycopg do all the argument substitution here
402 # as it will quote all the params like the table name. That
403 # doesn't work. So, we substitute a "%s" for "%s" here so we
404 # keep it after python's own string substitution.
Steve McIntyre05e3e622015-09-25 01:29:18 +0100405 sql = "SELECT %s FROM %s WHERE %s = %s AND %s = %s ORDER by %s ASC" % (select_field, table, compare_field1, "%s", compare_field2, "%s", sort_field)
Steve McIntyre7201c9b2014-12-17 17:33:51 +0000406
407 data = (value1, value2)
408 self.cursor.execute(sql, data)
409
410 if self.cursor.rowcount > 0:
411 results = []
412 for record in self.cursor:
413 results.append(record[0])
414 return results
415 else:
416 return None
417
Steve McIntyre2d685c72014-12-08 15:24:12 +0000418 # Simple lookup: look up a switch by ID, and return all the
419 # details of that switch.
420 #
421 # Returns None on failure.
Steve McIntyre549435f2014-12-05 15:42:46 +0000422 def get_switch_by_id(self, switch_id):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000423 return self._get_row("switch", "switch_id", int(switch_id))
Steve McIntyref3655062014-12-05 15:34:39 +0000424
Steve McIntyre2d685c72014-12-08 15:24:12 +0000425 # Simple lookup: look up a switch by name, and return the ID of
426 # that switch.
427 #
428 # Returns None on failure.
Steve McIntyre549435f2014-12-05 15:42:46 +0000429 def get_switch_id_by_name(self, name):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100430 return self._get_element("switch_id", "switch", "name", name)
Dave Pigott281203e2014-09-17 23:45:02 +0100431
Steve McIntyre2d685c72014-12-08 15:24:12 +0000432 # Simple lookup: look up a switch by ID, and return the name of
433 # that switch.
434 #
435 # Returns None on failure.
Steve McIntyre549435f2014-12-05 15:42:46 +0000436 def get_switch_name_by_id(self, switch_id):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000437 return self._get_element("name", "switch", "switch_id", int(switch_id))
Dave Pigott281203e2014-09-17 23:45:02 +0100438
Steve McIntyre2d685c72014-12-08 15:24:12 +0000439 # Simple lookup: look up a port by ID, and return all the details
440 # of that port.
441 #
442 # Returns None on failure.
Steve McIntyre549435f2014-12-05 15:42:46 +0000443 def get_port_by_id(self, port_id):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000444 return self._get_row("port", "port_id", int(port_id))
Steve McIntyref3655062014-12-05 15:34:39 +0000445
Steve McIntyre2d685c72014-12-08 15:24:12 +0000446 # Simple lookup: look up a switch by ID, and return the IDs of all
447 # the ports on that switch.
448 #
449 # Returns None on failure.
Steve McIntyreb67f3912014-12-02 17:14:36 +0000450 def get_ports_by_switch(self, switch_id):
Steve McIntyre05e3e622015-09-25 01:29:18 +0100451 return self._get_multi_elements("port_id", "port", "switch_id", int(switch_id), "port_id")
Steve McIntyreb67f3912014-12-02 17:14:36 +0000452
Steve McIntyre7201c9b2014-12-17 17:33:51 +0000453 # More complex lookup: look up all the trunk ports on a switch by
454 # ID
455 #
456 # Returns None on failure.
457 def get_trunk_port_names_by_switch(self, switch_id):
Steve McIntyre05e3e622015-09-25 01:29:18 +0100458 return self._get_multi_elements2("name", "port", "switch_id", int(switch_id), "is_trunk", True, "port_id")
Steve McIntyre7201c9b2014-12-17 17:33:51 +0000459
Steve McIntyre2d685c72014-12-08 15:24:12 +0000460 # Simple lookup: look up a port by its name and its parent switch
461 # by ID, and return the ID of the port.
462 #
463 # Returns None on failure.
Steve McIntyre53a7bc82014-12-05 15:23:34 +0000464 def get_port_by_switch_and_name(self, switch_id, name):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000465 return self._get_element2("port_id", "port", "switch_id", int(switch_id), "name", name)
Steve McIntyre53a7bc82014-12-05 15:23:34 +0000466
Steve McIntyre45f55012015-08-05 13:55:15 +0100467 # Simple lookup: look up a port by its external name and its
468 # parent switch by ID, and return the ID of the port.
469 #
470 # Returns None on failure.
471 def get_port_by_switch_and_number(self, switch_id, number):
472 return self._get_element2("port_id", "port", "switch_id", int(switch_id), "number", int(number))
473
Steve McIntyre2d685c72014-12-08 15:24:12 +0000474 # Simple lookup: look up a port by ID, and return the current VLAN
475 # id of that port.
476 #
477 # Returns None on failure.
Steve McIntyredaae5502014-12-05 17:55:18 +0000478 def get_current_vlan_id_by_port(self, port_id):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000479 return self._get_element("current_vlan_id", "port", "port_id", int(port_id))
Steve McIntyredaae5502014-12-05 17:55:18 +0000480
Steve McIntyre2d685c72014-12-08 15:24:12 +0000481 # Simple lookup: look up a port by ID, and return the base VLAN
482 # id of that port.
483 #
484 # Returns None on failure.
Steve McIntyredaae5502014-12-05 17:55:18 +0000485 def get_base_vlan_id_by_port(self, port_id):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000486 return self._get_element("base_vlan_id", "port", "port_id", int(port_id))
Steve McIntyredaae5502014-12-05 17:55:18 +0000487
Steve McIntyre2d685c72014-12-08 15:24:12 +0000488 # Simple lookup: look up a current VLAN by ID, and return the IDs
489 # of all the ports on that VLAN.
490 #
491 # Returns None on failure.
Steve McIntyre53a7bc82014-12-05 15:23:34 +0000492 def get_ports_by_current_vlan(self, vlan_id):
Steve McIntyre05e3e622015-09-25 01:29:18 +0100493 return self._get_multi_elements("port_id", "port", "current_vlan_id", int(vlan_id), "port_id")
Steve McIntyre53a7bc82014-12-05 15:23:34 +0000494
Steve McIntyre2d685c72014-12-08 15:24:12 +0000495 # Simple lookup: look up a base VLAN by ID, and return the IDs
496 # of all the ports on that VLAN.
497 #
498 # Returns None on failure.
Steve McIntyre53a7bc82014-12-05 15:23:34 +0000499 def get_ports_by_base_vlan(self, vlan_id):
Steve McIntyre05e3e622015-09-25 01:29:18 +0100500 return self._get_multi_elements("port_id", "port", "base_vlan_id", int(vlan_id), "port_id")
Steve McIntyre53a7bc82014-12-05 15:23:34 +0000501
Steve McIntyrec4890132015-08-07 15:19:11 +0100502 # Simple lookup: look up a trunk by ID, and return the IDs of the
503 # ports on both ends of that trunk.
504 #
505 # Returns None on failure.
506 def get_ports_by_trunk(self, trunk_id):
Steve McIntyre05e3e622015-09-25 01:29:18 +0100507 return self._get_multi_elements("port_id", "port", "trunk_id", int(trunk_id), "port_id")
Steve McIntyrec4890132015-08-07 15:19:11 +0100508
Steve McIntyre2d685c72014-12-08 15:24:12 +0000509 # Simple lookup: look up a VLAN by ID, and return all the details
510 # of that VLAN.
511 #
512 # Returns None on failure.
Steve McIntyre549435f2014-12-05 15:42:46 +0000513 def get_vlan_by_id(self, vlan_id):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000514 return self._get_row("vlan", "vlan_id", int(vlan_id))
Steve McIntyref3655062014-12-05 15:34:39 +0000515
Steve McIntyre2d685c72014-12-08 15:24:12 +0000516 # Simple lookup: look up a VLAN by name, and return the ID of that
517 # VLAN.
518 #
519 # Returns None on failure.
Steve McIntyref3655062014-12-05 15:34:39 +0000520 def get_vlan_id_by_name(self, name):
521 return self._get_element("vlan_id", "vlan", "name", name)
522
Steve McIntyre2d685c72014-12-08 15:24:12 +0000523 # Simple lookup: look up a VLAN by tag, and return the ID of that
524 # VLAN.
525 #
526 # Returns None on failure.
Steve McIntyref3655062014-12-05 15:34:39 +0000527 def get_vlan_id_by_tag(self, tag):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000528 return self._get_element("vlan_id", "vlan", "tag", int(tag))
Steve McIntyref3655062014-12-05 15:34:39 +0000529
Steve McIntyre2d685c72014-12-08 15:24:12 +0000530 # Simple lookup: look up a VLAN by ID, and return the name of that
531 # VLAN.
532 #
533 # Returns None on failure.
Steve McIntyre549435f2014-12-05 15:42:46 +0000534 def get_vlan_name_by_id(self, vlan_id):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000535 return self._get_element("name", "vlan", "vlan_id", int(vlan_id))
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100536
Steve McIntyreb9b0aa52014-12-21 23:31:12 +0000537 # Simple lookup: look up a VLAN by ID, and return the tag of that
538 # VLAN.
539 #
540 # Returns None on failure.
541 def get_vlan_tag_by_id(self, vlan_id):
Steve McIntyre32e3a892015-01-23 17:47:46 +0000542 return self._get_element("tag", "vlan", "vlan_id", int(vlan_id))
Steve McIntyreb9b0aa52014-12-21 23:31:12 +0000543
Steve McIntyrec4890132015-08-07 15:19:11 +0100544 # Simple lookup: look up a trunk by ID, and return all the details
545 # of that trunk.
546 #
547 # Returns None on failure.
548 def get_trunk_by_id(self, trunk_id):
549 return self._get_row("trunk", "trunk_id", int(trunk_id))
550
Steve McIntyreea343aa2015-10-23 17:46:17 +0100551 # Get the last-modified time for the database
552 def get_last_modified_time(self):
553 sql = "SELECT last_modified FROM state"
554 self.cursor.execute(sql)
Steve McIntyreaf24aaa2015-10-23 17:59:04 +0100555 return self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +0100556
Steve McIntyre2d685c72014-12-08 15:24:12 +0000557 # Grab one row of a query on one column; useful as a quick wrapper
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100558 def _get_row(self, table, field, value):
Steve McIntyree0b842a2014-11-28 18:23:47 +0000559
560 # We really want to use psycopg's type handling deal with the
561 # (potentially) user-supplied data in the value field, so we
562 # have to pass (sql,data) through to cursor.execute. However,
563 # we can't have psycopg do all the argument substitution here
564 # as it will quote all the params like the table name. That
565 # doesn't work. So, we substitute a "%s" for "%s" here so we
566 # keep it after python's own string substitution.
567 sql = "SELECT * FROM %s WHERE %s = %s" % (table, field, "%s")
568
569 # Now, the next icky thing: we need to make sure that we're
570 # passing a dict so that psycopg2 can pick it apart properly
571 # for its own substitution code. We force this with the
572 # trailing comma here
573 data = (value, )
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000574 self.cursor.execute(sql, data)
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100575 return self.cursor.fetchone()
576
Steve McIntyre3330f4b2014-11-28 18:11:02 +0000577 # (Un)Lock a port in the database. This can only be done through
578 # the admin interface, and will stop API users from modifying
579 # settings on the port. Use this to lock down ports that are used
580 # for PDUs and other core infrastructure
581 def set_port_is_locked(self, port_id, is_locked):
Steve McIntyre8c64d952014-12-05 16:22:44 +0000582 port = self.get_port_by_id(port_id)
583 if port is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000584 raise NotFoundError("Port ID %d does not exist" % int(port_id))
Steve McIntyre3330f4b2014-11-28 18:11:02 +0000585 try:
Steve McIntyree1371102014-12-05 17:17:09 +0000586 sql = "UPDATE port SET is_locked=%s WHERE port_id=%s RETURNING port_id"
Steve McIntyre4b918132014-12-05 17:04:46 +0000587 data = (is_locked, port_id)
Steve McIntyre3330f4b2014-11-28 18:11:02 +0000588 self.cursor.execute(sql, data)
589 port_id = self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +0100590 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Steve McIntyre3330f4b2014-11-28 18:11:02 +0000591 self.connection.commit()
592 except:
593 self.connection.rollback()
594 raise
Steve McIntyre1c8a3212015-07-14 17:07:31 +0100595 return port_id
Steve McIntyre3330f4b2014-11-28 18:11:02 +0000596
Steve McIntyre4204d0d2014-12-05 16:24:10 +0000597 # Set the mode of a port in the database. Valid values for mode
598 # are "trunk" and "access"
599 def set_port_mode(self, port_id, mode):
600 port = self.get_port_by_id(port_id)
601 if port is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000602 raise NotFoundError("Port ID %d does not exist" % int(port_id))
Steve McIntyre4204d0d2014-12-05 16:24:10 +0000603 if mode == "access":
604 is_trunk = False
605 elif mode == "trunk":
606 is_trunk = True
607 else:
608 raise InputError("Port mode %s is not valid" % mode)
609 try:
Steve McIntyree1371102014-12-05 17:17:09 +0000610 sql = "UPDATE port SET is_trunk=%s WHERE port_id=%s RETURNING port_id"
Steve McIntyre4b918132014-12-05 17:04:46 +0000611 data = (is_trunk, port_id)
Steve McIntyre4204d0d2014-12-05 16:24:10 +0000612 self.cursor.execute(sql, data)
613 port_id = self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +0100614 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Steve McIntyre4204d0d2014-12-05 16:24:10 +0000615 self.connection.commit()
616 except:
617 self.connection.rollback()
618 raise
619 return port_id
620
Steve McIntyre2d685c72014-12-08 15:24:12 +0000621 # Set the current vlan of a port in the database. The VLAN is
622 # passed by ID.
623 #
624 # Constraints:
625 # 1. The port must already exist
626 # 2. The port must not be a trunk port
627 # 3. The port must not be locked
628 # 1. The VLAN must already exist in the database
Steve McIntyre9eb78652014-12-05 17:51:53 +0000629 def set_current_vlan(self, port_id, vlan_id):
Steve McIntyre549435f2014-12-05 15:42:46 +0000630 port = self.get_port_by_id(port_id)
Steve McIntyre028b3cc2014-12-05 16:24:46 +0000631 if port is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000632 raise NotFoundError("Port ID %d does not exist" % int(port_id))
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100633
Steve McIntyre6dd00be2014-12-05 17:29:35 +0000634 if port.is_trunk or port.is_locked:
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100635 raise CriticalError("The port is locked")
636
Steve McIntyre549435f2014-12-05 15:42:46 +0000637 vlan = self.get_vlan_by_id(vlan_id)
Steve McIntyre028b3cc2014-12-05 16:24:46 +0000638 if vlan is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000639 raise NotFoundError("VLAN ID %d does not exist" % int(vlan_id))
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100640
641 try:
Steve McIntyree1371102014-12-05 17:17:09 +0000642 sql = "UPDATE port SET current_vlan_id=%s WHERE port_id=%s RETURNING port_id"
Steve McIntyre4b918132014-12-05 17:04:46 +0000643 data = (vlan_id, port_id)
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000644 self.cursor.execute(sql, data)
Steve McIntyree1371102014-12-05 17:17:09 +0000645 port_id = self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +0100646 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Steve McIntyree1371102014-12-05 17:17:09 +0000647 self.connection.commit()
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100648 except:
649 self.connection.rollback()
650 raise
Steve McIntyree1371102014-12-05 17:17:09 +0000651 return port_id
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100652
Steve McIntyre2d685c72014-12-08 15:24:12 +0000653 # Set the base vlan of a port in the database. The VLAN is
654 # passed by ID.
655 #
656 # Constraints:
657 # 1. The port must already exist
658 # 2. The port must not be a trunk port
659 # 3. The port must not be locked
Steve McIntyree653d172015-08-06 16:51:18 +0100660 # 4. The VLAN must already exist in the database
Steve McIntyredaae5502014-12-05 17:55:18 +0000661 def set_base_vlan(self, port_id, vlan_id):
662 port = self.get_port_by_id(port_id)
663 if port is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000664 raise NotFoundError("Port ID %d does not exist" % int(port_id))
Steve McIntyredaae5502014-12-05 17:55:18 +0000665
666 if port.is_trunk or port.is_locked:
667 raise CriticalError("The port is locked")
668
669 vlan = self.get_vlan_by_id(vlan_id)
670 if vlan is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000671 raise NotFoundError("VLAN ID %d does not exist" % int(vlan_id))
Steve McIntyredaae5502014-12-05 17:55:18 +0000672 if not vlan.is_base_vlan:
673 raise InputError("VLAN ID %d is not a base VLAN" % int(vlan_id))
674
675 try:
676 sql = "UPDATE port SET base_vlan_id=%s WHERE port_id=%s RETURNING port_id"
677 data = (vlan_id, port_id)
678 self.cursor.execute(sql, data)
679 port_id = self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +0100680 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Steve McIntyredaae5502014-12-05 17:55:18 +0000681 self.connection.commit()
682 except:
683 self.connection.rollback()
684 raise
685 return port_id
686
Steve McIntyrec4890132015-08-07 15:19:11 +0100687 # Internal function: Attach a port to a trunk in the database.
688 #
689 # Constraints:
690 # 1. The port must already exist
691 # 2. The port must not be locked
692 def _set_port_trunk(self, port_id, trunk_id):
693 port = self.get_port_by_id(port_id)
694 if port is None:
Steve McIntyreb01959f2016-03-22 17:02:39 +0000695 raise NotFoundError("Port ID %d does not exist" % int(port_id))
Steve McIntyrec4890132015-08-07 15:19:11 +0100696 if port.is_locked:
697 raise CriticalError("The port is locked")
698 try:
699 sql = "UPDATE port SET trunk_id=%s WHERE port_id=%s RETURNING port_id"
700 data = (int(trunk_id), int(port_id))
701 self.cursor.execute(sql, data)
702 port_id = self.cursor.fetchone()[0]
Steve McIntyreea343aa2015-10-23 17:46:17 +0100703 self.cursor.execute("UPDATE state SET last_modified=%s", (datetime.datetime.now(),))
Steve McIntyrec4890132015-08-07 15:19:11 +0100704 self.connection.commit()
705 except:
706 self.connection.rollback()
707 raise
708 return port_id
709
Steve McIntyre2d685c72014-12-08 15:24:12 +0000710 # Trivial helper function to return all the rows in a given table
Steve McIntyree3fb49a2015-09-23 00:04:12 +0100711 def _dump_table(self, table, order):
Dave Pigott281203e2014-09-17 23:45:02 +0100712 result = []
Steve McIntyree3fb49a2015-09-23 00:04:12 +0100713 self.cursor.execute("SELECT * FROM %s ORDER by %s ASC" % (table, order))
Dave Pigott281203e2014-09-17 23:45:02 +0100714 record = self.cursor.fetchone()
715 while record != None:
Steve McIntyree73eb122014-11-27 15:18:47 +0000716 result.append(record)
Dave Pigott281203e2014-09-17 23:45:02 +0100717 record = self.cursor.fetchone()
718 return result
719
720 def all_switches(self):
Steve McIntyree3fb49a2015-09-23 00:04:12 +0100721 return self._dump_table("switch", "switch_id")
Dave Pigott281203e2014-09-17 23:45:02 +0100722
723 def all_ports(self):
Steve McIntyree3fb49a2015-09-23 00:04:12 +0100724 return self._dump_table("port", "port_id")
Dave Pigott281203e2014-09-17 23:45:02 +0100725
726 def all_vlans(self):
Steve McIntyree3fb49a2015-09-23 00:04:12 +0100727 return self._dump_table("vlan", "vlan_id")
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100728
Steve McIntyrec4890132015-08-07 15:19:11 +0100729 def all_trunks(self):
Steve McIntyree3fb49a2015-09-23 00:04:12 +0100730 return self._dump_table("trunk", "trunk_id")
Steve McIntyrec4890132015-08-07 15:19:11 +0100731
Steve McIntyre6a618162014-12-10 16:47:07 +0000732if __name__ == '__main__':
733 db = VlanDB()
Steve McIntyre6d84ec12014-12-18 16:56:56 +0000734 s = db.all_switches()
735 print 'The DB knows about %d switch(es)' % len(s)
736 print s
737 p = db.all_ports()
738 print 'The DB knows about %d port(s)' % len(p)
739 print p
740 v = db.all_vlans()
741 print 'The DB knows about %d vlan(s)' % len(v)
742 print v
Steve McIntyrec4890132015-08-07 15:19:11 +0100743 t = db.all_trunks()
744 print 'The DB knows about %d trunks(s)' % len(t)
745 print t
Steve McIntyre6a618162014-12-10 16:47:07 +0000746
Steve McIntyre6c4f33f2015-08-03 19:25:07 +0100747 print 'First free VLAN tag is %d' % db.find_lowest_unused_vlan_tag()