blob: 487bc31c9c8635578d5ca45c8eb412aab91265d7 [file] [log] [blame]
Dave Pigott281203e2014-09-17 23:45:02 +01001#! /usr/bin/python
2
3# Copyright 2014 Linaro Limited
Steve McIntyre663dc062014-10-20 11:11:47 +01004# Author: Dave Pigott <dave.pigott@linaro.org>
Dave Pigott281203e2014-09-17 23:45:02 +01005#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19# MA 02110-1301, USA.
20
21import psycopg2
22import psycopg2.extras
Steve McIntyred74d97c2014-11-28 14:44:39 +000023import datetime
Steve McIntyre6b013652014-12-02 12:35:18 +000024from errors import CriticalError, InputError
Dave Pigott281203e2014-09-17 23:45:02 +010025
26class VlanDB:
27 def __init__(self, db_name="vland", username="vland"):
28 try:
Steve McIntyree38f6222014-11-27 15:09:49 +000029 self.connection = psycopg2.connect(database=db_name, user=username)
30 self.cursor = self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
Dave Pigott281203e2014-09-17 23:45:02 +010031 except Exception as e:
32 print "Failed to access database: %s" % e
33
34 def __del__(self):
35 self.cursor.close()
36 self.connection.close()
37
Steve McIntyre8d39c792014-11-28 18:09:31 +000038 # Create a new switch in the database
Steve McIntyredbd7fe52014-11-27 16:54:29 +000039 def create_switch(self, name):
Dave Pigott2649a1a2014-09-18 00:04:49 +010040 try:
Steve McIntyredbd7fe52014-11-27 16:54:29 +000041 sql = "INSERT INTO switch (name) VALUES (%s) RETURNING switch_id"
42 data = name
43 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +010044 switch_id = self.cursor.fetchone()[0]
45 self.connection.commit()
46 except:
47 self.connection.rollback()
48 raise
Dave Pigott281203e2014-09-17 23:45:02 +010049 return switch_id
50
Steve McIntyre90a4a972014-11-28 16:50:56 +000051 # Create a new port in the database. Two of the fields are created
52 # with default values (is_locked, is_trunk) here, and should be
53 # updated separately if desired. For the current_vlan_id and
54 # base_vlan_id fields, *BE CAREFUL* that you have already looked
55 # up the correct VLAN_ID for each. This is *NOT* the same as the
56 # VLAN tag (likely to be 1).
57 # You Have Been Warned!
58 def create_port(self, name, switch_id, current_vlan_id, base_vlan_id):
Dave Pigott2649a1a2014-09-18 00:04:49 +010059 try:
Steve McIntyred74d97c2014-11-28 14:44:39 +000060 sql = "INSERT INTO port (name, switch_id, is_locked, is_trunk, current_vlan_id, base_vlan_id) VALUES (%s, %s, %s, %s, %s, %s) RETURNING port_id"
Steve McIntyre90a4a972014-11-28 16:50:56 +000061 data = (name, switch_id,
62 False, False,
63 current_vlan_id, base_vlan_id)
Steve McIntyredbd7fe52014-11-27 16:54:29 +000064 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +010065 port_id = self.cursor.fetchone()[0]
66 self.connection.commit()
67 except:
68 self.connection.rollback()
69 raise
Dave Pigott281203e2014-09-17 23:45:02 +010070 return port_id
71
Steve McIntyreb005a2f2014-11-28 18:23:05 +000072 # Create a new vlan in the database. We locally add a creation
73 # timestamp, for debug purposes. If vlans seems to be sticking
74 # around, we'll be able to see when they were created.
Steve McIntyredbd7fe52014-11-27 16:54:29 +000075 def create_vlan(self, name, tag, is_base_vlan):
Dave Pigott2649a1a2014-09-18 00:04:49 +010076 try:
Steve McIntyred74d97c2014-11-28 14:44:39 +000077 dt = datetime.datetime.now()
78 sql = "INSERT INTO vlan (name, tag, is_base_vlan, creation_time) VALUES (%s, %s, %s, %s) RETURNING vlan_id"
79 data = (name, tag, is_base_vlan, dt)
Steve McIntyredbd7fe52014-11-27 16:54:29 +000080 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +010081 vlan_id = self.cursor.fetchone()[0]
82 self.connection.commit()
83 except:
84 self.connection.rollback()
85 raise
Dave Pigott281203e2014-09-17 23:45:02 +010086 return vlan_id
87
88 def _delete_row(self, table, field, value):
Dave Pigott2649a1a2014-09-18 00:04:49 +010089 try:
Steve McIntyredbd7fe52014-11-27 16:54:29 +000090 sql = "DELETE FROM %s WHERE %s = %s"
91 data = (table, field, value)
92 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +010093 self.connection.commit()
94 except:
95 self.connection.rollback()
96 raise
Dave Pigott281203e2014-09-17 23:45:02 +010097
98 def delete_switch(self, switch_id):
99 self._delete_row("switch", "switch_id", switch_id)
100
101 def delete_port(self, port_id):
102 self._delete_row("port", "port_id", port_id)
103
104 def delete_vlan(self, vlan_id):
105 self._delete_row("vlan", "vlan_id", vlan_id)
106
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100107 def _get_element(self, select_field, table, compare_field, value):
Steve McIntyre95614c22014-11-28 17:02:44 +0000108
109 # We really want to use psycopg's type handling deal with the
110 # (potentially) user-supplied data in the value field, so we
111 # have to pass (sql,data) through to cursor.execute. However,
112 # we can't have psycopg do all the argument substitution here
113 # as it will quote all the params like the table name. That
114 # doesn't work. So, we substitute a "%s" for "%s" here so we
115 # keep it after python's own string substitution.
116 sql = "SELECT %s FROM %s WHERE %s = %s" % (select_field, table, compare_field, "%s")
117
118 # Now, the next icky thing: we need to make sure that we're
119 # passing a dict so that psycopg2 can pick it apart properly
120 # for its own substitution code. We force this with the
121 # trailing comma here
122 data = (value, )
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000123 self.cursor.execute(sql, data)
Steve McIntyre95614c22014-11-28 17:02:44 +0000124
125 # Will raise an exception here if there are no rows that
126 # match. That's OK - the caller needs to deal with that.
Dave Pigott281203e2014-09-17 23:45:02 +0100127 return self.cursor.fetchone()[0]
128
129 def get_switch_id(self, name):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100130 return self._get_element("switch_id", "switch", "name", name)
Dave Pigott281203e2014-09-17 23:45:02 +0100131
132 def get_port_id(self, name):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100133 return self._get_element("port_id", "port", "name", name)
Dave Pigott281203e2014-09-17 23:45:02 +0100134
Steve McIntyre9f403e82014-11-28 18:10:09 +0000135 def get_vlan_id_from_name(self, name):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100136 return self._get_element("vlan_id", "vlan", "name", name)
Dave Pigott281203e2014-09-17 23:45:02 +0100137
Steve McIntyre9f403e82014-11-28 18:10:09 +0000138 def get_vlan_id_from_tag(self, tag):
139 return self._get_element("vlan_id", "vlan", "tag", tag)
140
Dave Pigott281203e2014-09-17 23:45:02 +0100141 def get_switch_name(self, switch_id):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100142 return self._get_element("name", "switch", "switch_id", switch_id)
Dave Pigott281203e2014-09-17 23:45:02 +0100143
144 def get_port_name(self, port_id):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100145 return self._get_element("port_name", "port", "port_id", port_id)
Dave Pigott281203e2014-09-17 23:45:02 +0100146
147 def get_vlan_name(self, vlan_id):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100148 return self._get_element("vlan_name", "vlan", "vlan_id", vlan_id)
149
150 def _get_row(self, table, field, value):
Steve McIntyree0b842a2014-11-28 18:23:47 +0000151
152 # We really want to use psycopg's type handling deal with the
153 # (potentially) user-supplied data in the value field, so we
154 # have to pass (sql,data) through to cursor.execute. However,
155 # we can't have psycopg do all the argument substitution here
156 # as it will quote all the params like the table name. That
157 # doesn't work. So, we substitute a "%s" for "%s" here so we
158 # keep it after python's own string substitution.
159 sql = "SELECT * FROM %s WHERE %s = %s" % (table, field, "%s")
160
161 # Now, the next icky thing: we need to make sure that we're
162 # passing a dict so that psycopg2 can pick it apart properly
163 # for its own substitution code. We force this with the
164 # trailing comma here
165 data = (value, )
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000166 self.cursor.execute(sql, data)
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100167 return self.cursor.fetchone()
168
169 def get_switch(self, switch_id):
170 return self._get_row("switch", "switch_id", switch_id)
171
172 def get_port(self, port_id):
173 return self._get_row("port", "port_id", port_id)
174
175 def get_vlan(self, vlan_id):
176 return self._get_row("vlan", "vlan_id", vlan_id)
177
Steve McIntyre3330f4b2014-11-28 18:11:02 +0000178 # (Un)Lock a port in the database. This can only be done through
179 # the admin interface, and will stop API users from modifying
180 # settings on the port. Use this to lock down ports that are used
181 # for PDUs and other core infrastructure
182 def set_port_is_locked(self, port_id, is_locked):
183 try:
184 sql = "UPDATE port SET is_locked=%s WHERE port_id=%s"
185 data = (is_locked, port_id)
186 self.cursor.execute(sql, data)
187 port_id = self.cursor.fetchone()[0]
188 self.connection.commit()
189 except:
190 self.connection.rollback()
191 raise
192 return port_id
193
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100194 def set_vlan(self, port_id, vlan_id):
195 port = self.get_port(port_id)
196 if port == None:
197 raise("Port %s does not exist" % port_id)
198
199 if port["is_trunk"] or port["is_locked"]:
200 raise CriticalError("The port is locked")
201
202 vlan = self.get_vlan(vlan_id)
203 if vlan == None:
204 raise CriticalError("VLAN %s does not exist" % vlan_id)
205
206 try:
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000207 sql = "UPDATE port SET current_vlan_id=%s WHERE port_id=%s"
208 data = (vlan_id, port_id)
209 self.cursor.execute(sql, data)
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100210 except:
211 self.connection.rollback()
212 raise
213
214 def restore_default_vlan(self, port_id):
215 port = self.get_port(port_id)
216 if port == None:
217 raise CriticalError("Port %s does not exist")
218
219 if port["is_trunk"] or port["is_locked"]:
220 raise CriticalError("The port is locked")
221
222 try:
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000223 sql = "UPDATE port SET current_vlan_id=base_vlan_id WHERE port_id=%d"
224 data = port_id
225 self.cursor.execute(sql, data)
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100226 except:
227 self.connection.rollback()
228 raise
229
Dave Pigott281203e2014-09-17 23:45:02 +0100230 def _dump_table(self, table):
231 result = []
232 self.cursor.execute("SELECT * FROM %s" % table)
Dave Pigott281203e2014-09-17 23:45:02 +0100233 record = self.cursor.fetchone()
234 while record != None:
Steve McIntyree73eb122014-11-27 15:18:47 +0000235 result.append(record)
Dave Pigott281203e2014-09-17 23:45:02 +0100236 record = self.cursor.fetchone()
237 return result
238
239 def all_switches(self):
240 return self._dump_table("switch")
241
242 def all_ports(self):
243 return self._dump_table("port")
244
245 def all_vlans(self):
246 return self._dump_table("vlan")
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100247