2 # Functions for interacting with the nodegroups table in the database
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
7 # $Id: NodeGroups.py,v 1.2 2006/09/06 16:03:24 mlhuang Exp $
10 from types import StringTypes
12 from PLC.Faults import *
13 from PLC.Parameter import Parameter
14 from PLC.Debug import profile
15 from PLC.Table import Row, Table
16 from PLC.Nodes import Node, Nodes
20 Representation of a row in the nodegroups table. To use, optionally
21 instantiate with a dict of values. Update as you would a
22 dict. Commit to the database with flush().
26 'nodegroup_id': Parameter(int, "Node group identifier"),
27 'name': Parameter(str, "Node group name"),
28 'description': Parameter(str, "Node group description"),
29 'is_custom': Parameter(bool, "Is a custom node group (i.e., is not a site node group)")
32 # These fields are derived from join tables and are not
33 # actually in the nodegroups table.
35 'node_ids': Parameter([int], "List of nodes in this node group"),
38 def __init__(self, api, fields):
39 Row.__init__(self, fields)
42 def validate_name(self, name):
43 conflicts = NodeGroups(self.api, [name])
44 for nodegroup_id in conflicts:
45 if 'nodegroup_id' not in self or self['nodegroup_id'] != nodegroup_id:
46 raise PLCInvalidArgument, "Node group name already in use"
48 def add_node(self, node, commit = True):
50 Add node to existing nodegroup.
53 assert 'nodegroup_id' in self
54 assert isinstance(node, Node)
55 assert 'node_id' in node
57 node_id = node['node_id']
58 nodegroup_id = self['nodegroup_id']
59 self.api.db.do("INSERT INTO nodegroup_nodes (nodegroup_id, node_id)" \
60 " VALUES(%(nodegroup_id)d, %(node_id)d)",
66 if 'node_ids' in self and node_id not in self['node_ids']:
67 self['node_ids'].append(node_id)
69 if 'nodegroup_ids' in node and nodegroup_id not in node['nodegroup_ids']:
70 node['nodegroup_ids'].append(nodegroup_id)
72 def remove_node(self, node, commit = True):
74 Remove node from existing nodegroup.
77 assert 'nodegroup_id' in self
78 assert isinstance(node, Node)
79 assert 'node_id' in node
81 node_id = node['node_id']
82 nodegroup_id = self['nodegroup_id']
83 self.api.db.do("INSERT INTO nodegroup_nodes (nodegroup_id, node_id)" \
84 " VALUES(%(nodegroup_id)d, %(node_id)d)",
90 if 'node_ids' in self and node_id not in self['node_ids']:
91 self['node_ids'].append(node_id)
93 if 'nodegroup_ids' in node and nodegroup_id not in node['nodegroup_ids']:
94 node['nodegroup_ids'].append(nodegroup_id)
96 def flush(self, commit = True):
98 Flush changes back to the database.
103 # Fetch a new nodegroup_id if necessary
104 if 'nodegroup_id' not in self:
105 rows = self.api.db.selectall("SELECT NEXTVAL('nodegroups_nodegroup_id_seq') AS nodegroup_id")
107 raise PLCDBError, "Unable to fetch new nodegroup_id"
108 self['nodegroup_id'] = rows[0]['nodegroup_id']
113 # Filter out fields that cannot be set or updated directly
114 fields = dict(filter(lambda (key, value): key in self.fields,
117 # Parameterize for safety
119 values = [self.api.db.param(key, value) for (key, value) in fields.items()]
122 # Insert new row in nodegroups table
123 sql = "INSERT INTO nodegroups (%s) VALUES (%s)" % \
124 (", ".join(keys), ", ".join(values))
126 # Update existing row in sites table
127 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
128 sql = "UPDATE nodegroups SET " + \
129 ", ".join(columns) + \
130 " WHERE nodegroup_id = %(nodegroup_id)d"
132 self.api.db.do(sql, fields)
137 def delete(self, commit = True):
139 Delete existing nodegroup from the database.
142 assert 'nodegroup_id' in self
145 tables = ['nodegroup_nodes', 'override_bootscripts',
146 'conf_assoc', 'node_root_access']
148 if self['is_custom']:
149 tables.append('nodegroups')
151 # XXX Cannot delete site node groups yet
155 self.api.db.do("DELETE FROM %s" \
156 " WHERE nodegroup_id = %(nodegroup_id)" % \
162 class NodeGroups(Table):
164 Representation of row(s) from the nodegroups table in the
168 def __init__(self, api, nodegroup_id_or_name_list = None):
171 # N.B.: Node IDs returned may be deleted.
172 sql = "SELECT nodegroups.*, nodegroup_nodes.node_id" \
174 " LEFT JOIN nodegroup_nodes USING (nodegroup_id)"
176 if nodegroup_id_or_name_list:
177 # Separate the list into integers and strings
178 nodegroup_ids = filter(lambda nodegroup_id: isinstance(nodegroup_id, (int, long)),
179 nodegroup_id_or_name_list)
180 names = filter(lambda name: isinstance(name, StringTypes),
181 nodegroup_id_or_name_list)
182 sql += " WHERE (False"
184 sql += " OR nodegroup_id IN (%s)" % ", ".join(map(str, nodegroup_ids))
186 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names)).lower()
189 rows = self.api.db.selectall(sql)
191 if self.has_key(row['nodegroup_id']):
192 nodegroup = self[row['nodegroup_id']]
193 nodegroup.update(row)
195 self[row['nodegroup_id']] = NodeGroup(api, row)