blob: 14c36ffa02ea60cbf3ff77b370812618194f135d [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 McIntyre31d6dfa2014-12-02 12:35:56 +000038 # Create a new switch in the database. Switches are really simple
39 # devices - they're just containers for ports.
40 #
41 # Constraints:
42 # Switches must be uniquely named
Steve McIntyredbd7fe52014-11-27 16:54:29 +000043 def create_switch(self, name):
Steve McIntyre31d6dfa2014-12-02 12:35:56 +000044
45 switch_id = self.get_switch_id(name)
46 if switch_id is not None:
47 raise InputError("Switch name %s already exists" % name)
48
Dave Pigott2649a1a2014-09-18 00:04:49 +010049 try:
Steve McIntyredbd7fe52014-11-27 16:54:29 +000050 sql = "INSERT INTO switch (name) VALUES (%s) RETURNING switch_id"
Steve McIntyre31d6dfa2014-12-02 12:35:56 +000051 data = (name, )
Steve McIntyredbd7fe52014-11-27 16:54:29 +000052 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +010053 switch_id = self.cursor.fetchone()[0]
54 self.connection.commit()
55 except:
56 self.connection.rollback()
57 raise
Dave Pigott281203e2014-09-17 23:45:02 +010058 return switch_id
59
Steve McIntyre90a4a972014-11-28 16:50:56 +000060 # Create a new port in the database. Two of the fields are created
61 # with default values (is_locked, is_trunk) here, and should be
62 # updated separately if desired. For the current_vlan_id and
63 # base_vlan_id fields, *BE CAREFUL* that you have already looked
64 # up the correct VLAN_ID for each. This is *NOT* the same as the
65 # VLAN tag (likely to be 1).
66 # You Have Been Warned!
67 def create_port(self, name, switch_id, current_vlan_id, base_vlan_id):
Dave Pigott2649a1a2014-09-18 00:04:49 +010068 try:
Steve McIntyred74d97c2014-11-28 14:44:39 +000069 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 +000070 data = (name, switch_id,
71 False, False,
72 current_vlan_id, base_vlan_id)
Steve McIntyredbd7fe52014-11-27 16:54:29 +000073 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +010074 port_id = self.cursor.fetchone()[0]
75 self.connection.commit()
76 except:
77 self.connection.rollback()
78 raise
Dave Pigott281203e2014-09-17 23:45:02 +010079 return port_id
80
Steve McIntyreb005a2f2014-11-28 18:23:05 +000081 # Create a new vlan in the database. We locally add a creation
82 # timestamp, for debug purposes. If vlans seems to be sticking
83 # around, we'll be able to see when they were created.
Steve McIntyredbd7fe52014-11-27 16:54:29 +000084 def create_vlan(self, name, tag, is_base_vlan):
Dave Pigott2649a1a2014-09-18 00:04:49 +010085 try:
Steve McIntyred74d97c2014-11-28 14:44:39 +000086 dt = datetime.datetime.now()
87 sql = "INSERT INTO vlan (name, tag, is_base_vlan, creation_time) VALUES (%s, %s, %s, %s) RETURNING vlan_id"
88 data = (name, tag, is_base_vlan, dt)
Steve McIntyredbd7fe52014-11-27 16:54:29 +000089 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +010090 vlan_id = self.cursor.fetchone()[0]
91 self.connection.commit()
92 except:
93 self.connection.rollback()
94 raise
Dave Pigott281203e2014-09-17 23:45:02 +010095 return vlan_id
96
97 def _delete_row(self, table, field, value):
Dave Pigott2649a1a2014-09-18 00:04:49 +010098 try:
Steve McIntyredbd7fe52014-11-27 16:54:29 +000099 sql = "DELETE FROM %s WHERE %s = %s"
100 data = (table, field, value)
101 self.cursor.execute(sql, data)
Dave Pigott2649a1a2014-09-18 00:04:49 +0100102 self.connection.commit()
103 except:
104 self.connection.rollback()
105 raise
Dave Pigott281203e2014-09-17 23:45:02 +0100106
107 def delete_switch(self, switch_id):
108 self._delete_row("switch", "switch_id", switch_id)
109
110 def delete_port(self, port_id):
111 self._delete_row("port", "port_id", port_id)
112
113 def delete_vlan(self, vlan_id):
114 self._delete_row("vlan", "vlan_id", vlan_id)
115
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100116 def _get_element(self, select_field, table, compare_field, value):
Steve McIntyre95614c22014-11-28 17:02:44 +0000117
118 # We really want to use psycopg's type handling deal with the
119 # (potentially) user-supplied data in the value field, so we
120 # have to pass (sql,data) through to cursor.execute. However,
121 # we can't have psycopg do all the argument substitution here
122 # as it will quote all the params like the table name. That
123 # doesn't work. So, we substitute a "%s" for "%s" here so we
124 # keep it after python's own string substitution.
125 sql = "SELECT %s FROM %s WHERE %s = %s" % (select_field, table, compare_field, "%s")
126
127 # Now, the next icky thing: we need to make sure that we're
128 # passing a dict so that psycopg2 can pick it apart properly
129 # for its own substitution code. We force this with the
130 # trailing comma here
131 data = (value, )
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000132 self.cursor.execute(sql, data)
Steve McIntyre95614c22014-11-28 17:02:44 +0000133
134 # Will raise an exception here if there are no rows that
135 # match. That's OK - the caller needs to deal with that.
Dave Pigott281203e2014-09-17 23:45:02 +0100136 return self.cursor.fetchone()[0]
137
138 def get_switch_id(self, name):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100139 return self._get_element("switch_id", "switch", "name", name)
Dave Pigott281203e2014-09-17 23:45:02 +0100140
141 def get_port_id(self, name):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100142 return self._get_element("port_id", "port", "name", name)
Dave Pigott281203e2014-09-17 23:45:02 +0100143
Steve McIntyre9f403e82014-11-28 18:10:09 +0000144 def get_vlan_id_from_name(self, name):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100145 return self._get_element("vlan_id", "vlan", "name", name)
Dave Pigott281203e2014-09-17 23:45:02 +0100146
Steve McIntyre9f403e82014-11-28 18:10:09 +0000147 def get_vlan_id_from_tag(self, tag):
148 return self._get_element("vlan_id", "vlan", "tag", tag)
149
Dave Pigott281203e2014-09-17 23:45:02 +0100150 def get_switch_name(self, switch_id):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100151 return self._get_element("name", "switch", "switch_id", switch_id)
Dave Pigott281203e2014-09-17 23:45:02 +0100152
153 def get_port_name(self, port_id):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100154 return self._get_element("port_name", "port", "port_id", port_id)
Dave Pigott281203e2014-09-17 23:45:02 +0100155
156 def get_vlan_name(self, vlan_id):
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100157 return self._get_element("vlan_name", "vlan", "vlan_id", vlan_id)
158
159 def _get_row(self, table, field, value):
Steve McIntyree0b842a2014-11-28 18:23:47 +0000160
161 # We really want to use psycopg's type handling deal with the
162 # (potentially) user-supplied data in the value field, so we
163 # have to pass (sql,data) through to cursor.execute. However,
164 # we can't have psycopg do all the argument substitution here
165 # as it will quote all the params like the table name. That
166 # doesn't work. So, we substitute a "%s" for "%s" here so we
167 # keep it after python's own string substitution.
168 sql = "SELECT * FROM %s WHERE %s = %s" % (table, field, "%s")
169
170 # Now, the next icky thing: we need to make sure that we're
171 # passing a dict so that psycopg2 can pick it apart properly
172 # for its own substitution code. We force this with the
173 # trailing comma here
174 data = (value, )
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000175 self.cursor.execute(sql, data)
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100176 return self.cursor.fetchone()
177
178 def get_switch(self, switch_id):
179 return self._get_row("switch", "switch_id", switch_id)
180
181 def get_port(self, port_id):
182 return self._get_row("port", "port_id", port_id)
183
184 def get_vlan(self, vlan_id):
185 return self._get_row("vlan", "vlan_id", vlan_id)
186
Steve McIntyre3330f4b2014-11-28 18:11:02 +0000187 # (Un)Lock a port in the database. This can only be done through
188 # the admin interface, and will stop API users from modifying
189 # settings on the port. Use this to lock down ports that are used
190 # for PDUs and other core infrastructure
191 def set_port_is_locked(self, port_id, is_locked):
192 try:
193 sql = "UPDATE port SET is_locked=%s WHERE port_id=%s"
194 data = (is_locked, port_id)
195 self.cursor.execute(sql, data)
196 port_id = self.cursor.fetchone()[0]
197 self.connection.commit()
198 except:
199 self.connection.rollback()
200 raise
201 return port_id
202
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100203 def set_vlan(self, port_id, vlan_id):
204 port = self.get_port(port_id)
205 if port == None:
206 raise("Port %s does not exist" % port_id)
207
208 if port["is_trunk"] or port["is_locked"]:
209 raise CriticalError("The port is locked")
210
211 vlan = self.get_vlan(vlan_id)
212 if vlan == None:
213 raise CriticalError("VLAN %s does not exist" % vlan_id)
214
215 try:
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000216 sql = "UPDATE port SET current_vlan_id=%s WHERE port_id=%s"
217 data = (vlan_id, port_id)
218 self.cursor.execute(sql, data)
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100219 except:
220 self.connection.rollback()
221 raise
222
223 def restore_default_vlan(self, port_id):
224 port = self.get_port(port_id)
225 if port == None:
226 raise CriticalError("Port %s does not exist")
227
228 if port["is_trunk"] or port["is_locked"]:
229 raise CriticalError("The port is locked")
230
231 try:
Steve McIntyredbd7fe52014-11-27 16:54:29 +0000232 sql = "UPDATE port SET current_vlan_id=base_vlan_id WHERE port_id=%d"
233 data = port_id
234 self.cursor.execute(sql, data)
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100235 except:
236 self.connection.rollback()
237 raise
238
Dave Pigott281203e2014-09-17 23:45:02 +0100239 def _dump_table(self, table):
240 result = []
241 self.cursor.execute("SELECT * FROM %s" % table)
Dave Pigott281203e2014-09-17 23:45:02 +0100242 record = self.cursor.fetchone()
243 while record != None:
Steve McIntyree73eb122014-11-27 15:18:47 +0000244 result.append(record)
Dave Pigott281203e2014-09-17 23:45:02 +0100245 record = self.cursor.fetchone()
246 return result
247
248 def all_switches(self):
249 return self._dump_table("switch")
250
251 def all_ports(self):
252 return self._dump_table("port")
253
254 def all_vlans(self):
255 return self._dump_table("vlan")
Dave Pigott9b73f3a2014-09-18 22:55:42 +0100256