2 # Functions for interacting with the nodes table in the database
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
7 # $Id: Nodes.py,v 1.3 2006/09/19 19:28:39 mlhuang Exp $
10 from types import StringTypes
13 from PLC.Faults import *
14 from PLC.Parameter import Parameter
15 from PLC.Debug import profile
16 from PLC.Table import Row, Table
17 from PLC.NodeNetworks import NodeNetwork, NodeNetworks
18 from PLC.BootStates import BootStates
22 Representation of a row in the nodes table. To use, optionally
23 instantiate with a dict of values. Update as you would a
24 dict. Commit to the database with sync().
28 'node_id': Parameter(int, "Node identifier"),
29 'hostname': Parameter(str, "Fully qualified hostname", max = 255),
30 'site_id': Parameter(int, "Site at which this node is located"),
31 'boot_state': Parameter(str, "Boot state", max = 20),
32 'model': Parameter(str, "Make and model of the actual machine", max = 255),
33 'boot_nonce': Parameter(str, "(Admin only) Random value generated by the node at last boot", max = 128),
34 'version': Parameter(str, "Apparent Boot CD version", max = 64),
35 'ssh_rsa_key': Parameter(str, "Last known SSH host key", max = 1024),
36 'date_created': Parameter(str, "Date and time when node entry was created"),
37 'last_updated': Parameter(str, "Date and time when node entry was created"),
38 'deleted': Parameter(bool, "Has been deleted"),
39 'key': Parameter(str, "(Admin only) Node key", max = 256),
40 'session': Parameter(str, "(Admin only) Node session value", max = 256),
41 'nodenetwork_ids': Parameter([int], "List of network interfaces that this node has"),
42 'nodegroup_ids': Parameter([int], "List of node groups that this node is in"),
43 # 'conf_file_ids': Parameter([int], "List of configuration files specific to this node"),
44 # 'root_person_ids': Parameter([int], "(Admin only) List of people who have root access to this node"),
45 # 'slice_ids': Parameter([int], "List of slices on this node"),
46 # 'pcu_ids': Parameter([int], "List of PCUs that control this node"),
49 def __init__(self, api, fields):
50 Row.__init__(self, fields)
53 def validate_hostname(self, hostname):
54 # 1. Each part begins and ends with a letter or number.
55 # 2. Each part except the last can contain letters, numbers, or hyphens.
56 # 3. Each part is between 1 and 64 characters, including the trailing dot.
57 # 4. At least two parts.
58 # 5. Last part can only contain between 2 and 6 letters.
59 good_hostname = r'^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+' \
62 not re.match(good_hostname, hostname, re.IGNORECASE):
63 raise PLCInvalidArgument, "Invalid hostname"
65 conflicts = Nodes(self.api, [hostname])
66 for node_id, node in conflicts.iteritems():
67 if not node['deleted'] and ('node_id' not in self or self['node_id'] != node_id):
68 raise PLCInvalidArgument, "Hostname already in use"
70 # Check for conflicts with a nodenetwork hostname
71 conflicts = NodeNetworks(self.api, [hostname])
72 for nodenetwork_id in conflicts:
73 if 'nodenetwork_ids' not in self or nodenetwork_id not in self['nodenetwork_ids']:
74 raise PLCInvalidArgument, "Hostname already in use"
78 def validate_boot_state(self, boot_state):
79 if boot_state not in BootStates(self.api):
80 raise PLCInvalidArgument, "Invalid boot state"
84 def add_node_network(self, nodenetwork, commit = True):
86 Add node network to this node.
89 assert 'node_id' in self
90 assert isinstance(nodenetwork, NodeNetwork)
91 assert 'nodenetwork_id' in nodenetwork
93 nodenetwork_id = nodenetwork['nodenetwork_id']
94 nodenetwork['node_id'] = self['node_id']
96 self.api.db.do("INSERT INTO node_nodenetwork (node_id, nodenetwork_id, is_primary)" \
97 " VALUES(%(node_id)d, %(nodenetwork_id)d, False)",
103 if 'nodenetwork_ids' in self and nodenetwork_id not in self['nodenetwork_ids']:
104 self['nodenetwork_ids'].append(nodenetwork_id)
106 def set_primary_node_network(self, nodenetwork, commit = True):
108 Remove node network from this node.
111 assert 'node_id' in self
112 assert isinstance(nodenetwork, NodeNetwork)
113 assert 'nodenetwork_id' in nodenetwork
115 node_id = self['node_id']
116 nodenetwork_id = nodenetwork['nodenetwork_id']
118 self.api.db.do("UPDATE node_nodenetwork SET is_primary = False" \
119 " WHERE node_id = %(node_id)d",
122 self.api.db.do("UPDATE node_nodenetwork SET is_primary = True" \
123 " WHERE node_id = %(node_id)d" \
124 " AND nodenetwork_id = %(nodenetwork_id)d",
130 nodenetwork['is_primary'] = True
132 def sync(self, commit = True):
134 Flush changes back to the database.
139 # Fetch a new node_id if necessary
140 if 'node_id' not in self:
141 rows = self.api.db.selectall("SELECT NEXTVAL('nodes_node_id_seq') AS node_id")
143 raise PLCDBError, "Unable to fetch new node_id"
144 self['node_id'] = rows[0]['node_id']
149 # Filter out fields that cannot be set or updated directly
150 nodes_fields = self.api.db.fields('nodes')
151 fields = dict(filter(lambda (key, value): key in nodes_fields,
154 # Parameterize for safety
156 values = [self.api.db.param(key, value) for (key, value) in fields.items()]
159 # Insert new row in nodes table
160 sql = "INSERT INTO nodes (%s) VALUES (%s)" % \
161 (", ".join(keys), ", ".join(values))
163 # Update existing row in nodes table
164 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
165 sql = "UPDATE nodes SET " + \
166 ", ".join(columns) + \
167 " WHERE node_id = %(node_id)d"
169 self.api.db.do(sql, fields)
174 def delete(self, commit = True):
176 Delete existing node.
179 assert 'node_id' in self
181 # Delete all nodenetworks
182 nodenetworks = NodeNetworks(self.api, self['nodenetwork_ids'])
183 for nodenetwork in nodenetworks.values():
184 nodenetwork.delete(commit = False)
186 # Clean up miscellaneous join tables
187 for table in ['nodegroup_node']:
188 self.api.db.do("DELETE FROM %s" \
189 " WHERE node_id = %d" % \
190 (table, self['node_id']))
193 self['deleted'] = True
198 Representation of row(s) from the nodes table in the
202 def __init__(self, api, node_id_or_hostname_list = None, fields = Node.fields.keys()):
205 sql = "SELECT %s FROM view_nodes WHERE deleted IS False" % \
208 if node_id_or_hostname_list:
209 # Separate the list into integers and strings
210 node_ids = filter(lambda node_id: isinstance(node_id, (int, long)),
211 node_id_or_hostname_list)
212 hostnames = filter(lambda hostname: isinstance(hostname, StringTypes),
213 node_id_or_hostname_list)
216 sql += " OR node_id IN (%s)" % ", ".join(map(str, node_ids))
218 sql += " OR hostname IN (%s)" % ", ".join(api.db.quote(hostnames)).lower()
221 rows = self.api.db.selectall(sql)
224 self[row['node_id']] = node = Node(api, row)
225 for aggregate in ['nodenetwork_ids', 'nodegroup_ids',
226 'conf_file_ids', 'root_person_ids', 'slice_ids',
228 if not node.has_key(aggregate) or node[aggregate] is None:
231 node[aggregate] = map(int, node[aggregate].split(','))