2 # Functions for interacting with the nodenetworks table in the database
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
10 from types import StringTypes
14 from PLC.Faults import *
15 from PLC.Parameter import Parameter
16 from PLC.Debug import profile
17 from PLC.Table import Row, Table
20 def in_same_network(address1, address2, netmask):
22 Returns True if two IPv4 addresses are in the same network. Faults
23 if an address is invalid.
26 address1 = struct.unpack('>L', socket.inet_aton(address1))[0]
27 address2 = struct.unpack('>L', socket.inet_aton(address2))[0]
28 netmask = struct.unpack('>L', socket.inet_aton(netmask))[0]
30 return (address1 & netmask) == (address2 & netmask)
32 class NodeNetwork(Row):
34 Representation of a row in the nodenetworks table. To use, optionally
35 instantiate with a dict of values. Update as you would a
36 dict. Commit to the database with flush().
40 'nodenetwork_id': Parameter(int, "Node interface identifier"),
41 'method': Parameter(str, "Addressing method (e.g., 'static' or 'dhcp')"),
42 'type': Parameter(str, "Address type (e.g., 'ipv4')"),
43 'ip': Parameter(str, "IP address"),
44 'mac': Parameter(str, "MAC address"),
45 'gateway': Parameter(str, "IP address of primary gateway"),
46 'network': Parameter(str, "Subnet address"),
47 'broadcast': Parameter(str, "Network broadcast address"),
48 'netmask': Parameter(str, "Subnet mask"),
49 'dns1': Parameter(str, "IP address of primary DNS server"),
50 'dns2': Parameter(str, "IP address of secondary DNS server"),
51 # XXX Should be an int (bps)
52 'bwlimit': Parameter(str, "Bandwidth limit"),
53 'hostname': Parameter(str, "(Optional) Hostname"),
56 # These fields are derived from join tables and are not
57 # actually in the nodenetworks table.
59 'node_id': Parameter(int, "Node associated with this interface (if any)"),
60 'is_primary': Parameter(bool, "Is the primary interface for this node"),
63 methods = ['static', 'dhcp', 'proxy', 'tap', 'ipmi', 'unknown']
68 '100kbit', '250kbit', '500kbit',
69 '1mbit', '2mbit', '5mbit',
70 '10mbit', '20mbit', '50mbit',
73 def __init__(self, api, fields):
74 Row.__init__(self, fields)
77 def validate_method(self, method):
78 if method not in self.methods:
79 raise PLCInvalidArgument, "Invalid addressing method"
81 def validate_type(self, type):
82 if type not in self.types:
83 raise PLCInvalidArgument, "Invalid address type"
85 def validate_ip(self, ip):
87 ip = socket.inet_ntoa(socket.inet_aton(ip))
89 raise PLCInvalidArgument, "Invalid IP address " + ip
93 def validate_mac(self, mac):
95 bytes = mac.split(":")
98 for i, byte in enumerate(bytes):
100 if byte < 0 or byte > 255:
102 bytes[i] = "%02x" % byte
103 mac = ":".join(bytes)
105 raise PLCInvalidArgument, "Invalid MAC address"
109 validate_gateway = validate_ip
110 validate_network = validate_ip
111 validate_broadcast = validate_ip
112 validate_netmask = validate_ip
113 validate_dns1 = validate_ip
114 validate_dns2 = validate_ip
116 def validate_bwlimit(self, bwlimit):
117 if bwlimit not in self.bwlimits:
118 raise PLCInvalidArgument, "Invalid bandwidth limit"
120 def validate_hostname(self, hostname):
125 # Validate hostname, and check for conflicts with a node hostname
126 return PLC.Nodes.Node.validate_hostname(self, hostname)
128 def flush(self, commit = True):
130 Flush changes back to the database.
133 # Validate all specified fields
137 method = self['method']
140 raise PLCInvalidArgument, "method and type must both be specified"
142 if method == "proxy" or method == "tap":
144 raise PLCInvalidArgument, "For %s method, mac should not be specified" % method
146 raise PLCInvalidArgument, "For %s method, ip is required" % method
147 if method == "tap" and 'gateway' not in self:
148 raise PLCInvalidArgument, "For tap method, gateway is required and should be " \
149 "the IP address of the node that proxies for this address"
150 # Should check that the proxy address is reachable, but
151 # there's no way to tell if the only primary interface is
154 elif method == "static":
155 for key in ['ip', 'gateway', 'network', 'broadcast', 'netmask', 'dns1']:
157 raise PLCInvalidArgument, "For static method, %s is required" % key
158 locals()[key] = self[key]
159 if not in_same_network(ip, network, netmask):
160 raise PLCInvalidArgument, "IP address %s is inconsistent with network %s/%s" % \
161 (ip, network, netmask)
162 if not in_same_network(broadcast, network, netmask):
163 raise PLCInvalidArgument, "Broadcast address %s is inconsistent with network %s/%s" % \
164 (broadcast, network, netmask)
165 if not in_same_network(ip, gateway, netmask):
166 raise PLCInvalidArgument, "Gateway %s is not reachable from %s/%s" % \
167 (gateway, ip, netmask)
169 elif method == "ipmi":
171 raise PLCInvalidArgument, "For ipmi method, ip is required"
173 # Fetch a new nodenetwork_id if necessary
174 if 'nodenetwork_id' not in self:
175 rows = self.api.db.selectall("SELECT NEXTVAL('nodenetworks_nodenetwork_id_seq') AS nodenetwork_id")
177 raise PLCDBError("Unable to fetch new nodenetwork_id")
178 self['nodenetwork_id'] = rows[0]['nodenetwork_id']
183 # Filter out fields that cannot be set or updated directly
184 fields = dict(filter(lambda (key, value): key in self.fields,
187 # Parameterize for safety
189 values = [self.api.db.param(key, value) for (key, value) in fields.items()]
192 # Insert new row in nodenetworks table
193 sql = "INSERT INTO nodenetworks (%s) VALUES (%s)" % \
194 (", ".join(keys), ", ".join(values))
196 # Update existing row in sites table
197 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
198 sql = "UPDATE nodenetworks SET " + \
199 ", ".join(columns) + \
200 " WHERE nodenetwork_id = %(nodenetwork_id)d"
202 self.api.db.do(sql, fields)
207 def delete(self, commit = True):
209 Delete existing nodenetwork.
212 assert 'nodenetwork_id' in self
215 for table in ['node_nodenetworks', 'nodenetworks']:
216 self.api.db.do("DELETE FROM %s" \
217 " WHERE nodenetwork_id = %d" % \
218 (table, self['nodenetwork_id']))
223 class NodeNetworks(Table):
225 Representation of row(s) from the nodenetworks table in the
229 def __init__(self, api, nodenetwork_id_or_hostname_list = None):
232 # N.B.: Node IDs returned may be deleted.
233 sql = "SELECT nodenetworks.*" \
234 ", node_nodenetworks.node_id" \
235 ", node_nodenetworks.is_primary" \
236 " FROM nodenetworks" \
237 " LEFT JOIN node_nodenetworks USING (nodenetwork_id)"
239 if nodenetwork_id_or_hostname_list:
240 # Separate the list into integers and strings
241 nodenetwork_ids = filter(lambda nodenetwork_id: isinstance(nodenetwork_id, (int, long)),
242 nodenetwork_id_or_hostname_list)
243 hostnames = filter(lambda hostname: isinstance(hostname, StringTypes),
244 nodenetwork_id_or_hostname_list)
245 sql += " WHERE (False"
247 sql += " OR nodenetwork_id IN (%s)" % ", ".join(map(str, nodenetwork_ids))
249 sql += " OR hostname IN (%s)" % ", ".join(api.db.quote(hostnames)).lower()
252 rows = self.api.db.selectall(sql)
254 if self.has_key(row['nodenetwork_id']):
255 nodenetwork = self[row['nodenetwork_id']]
256 nodenetwork.update(row)
258 self[row['nodenetwork_id']] = NodeNetwork(api, row)