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.3 2006/09/07 23:44:49 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"
50 def add_node(self, node, commit = True):
52 Add node to existing nodegroup.
55 assert 'nodegroup_id' in self
56 assert isinstance(node, Node)
57 assert 'node_id' in node
59 node_id = node['node_id']
60 nodegroup_id = self['nodegroup_id']
61 self.api.db.do("INSERT INTO nodegroup_nodes (nodegroup_id, node_id)" \
62 " VALUES(%(nodegroup_id)d, %(node_id)d)",
68 if 'node_ids' in self and node_id not in self['node_ids']:
69 self['node_ids'].append(node_id)
71 if 'nodegroup_ids' in node and nodegroup_id not in node['nodegroup_ids']:
72 node['nodegroup_ids'].append(nodegroup_id)
74 def remove_node(self, node, commit = True):
76 Remove node from existing nodegroup.
79 assert 'nodegroup_id' in self
80 assert isinstance(node, Node)
81 assert 'node_id' in node
83 node_id = node['node_id']
84 nodegroup_id = self['nodegroup_id']
85 self.api.db.do("INSERT INTO nodegroup_nodes (nodegroup_id, node_id)" \
86 " VALUES(%(nodegroup_id)d, %(node_id)d)",
92 if 'node_ids' in self and node_id not in self['node_ids']:
93 self['node_ids'].append(node_id)
95 if 'nodegroup_ids' in node and nodegroup_id not in node['nodegroup_ids']:
96 node['nodegroup_ids'].append(nodegroup_id)
98 def flush(self, commit = True):
100 Flush changes back to the database.
105 # Fetch a new nodegroup_id if necessary
106 if 'nodegroup_id' not in self:
107 rows = self.api.db.selectall("SELECT NEXTVAL('nodegroups_nodegroup_id_seq') AS nodegroup_id")
109 raise PLCDBError, "Unable to fetch new nodegroup_id"
110 self['nodegroup_id'] = rows[0]['nodegroup_id']
115 # Filter out fields that cannot be set or updated directly
116 fields = dict(filter(lambda (key, value): key in self.fields,
119 # Parameterize for safety
121 values = [self.api.db.param(key, value) for (key, value) in fields.items()]
124 # Insert new row in nodegroups table
125 sql = "INSERT INTO nodegroups (%s) VALUES (%s)" % \
126 (", ".join(keys), ", ".join(values))
128 # Update existing row in sites table
129 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
130 sql = "UPDATE nodegroups SET " + \
131 ", ".join(columns) + \
132 " WHERE nodegroup_id = %(nodegroup_id)d"
134 self.api.db.do(sql, fields)
140 def delete(self, commit = True):
142 Delete existing nodegroup from the database.
145 assert 'nodegroup_id' in self
148 tables = ['nodegroup_nodes', 'override_bootscripts',
149 'conf_assoc', 'node_root_access']
151 if self['is_custom']:
152 tables.append('nodegroups')
154 # XXX Cannot delete site node groups yet
158 self.api.db.do("DELETE FROM %s" \
159 " WHERE nodegroup_id = %(nodegroup_id)" % \
165 class NodeGroups(Table):
167 Representation of row(s) from the nodegroups table in the
171 def __init__(self, api, nodegroup_id_or_name_list = None):
174 # N.B.: Node IDs returned may be deleted.
175 sql = "SELECT nodegroups.*, nodegroup_nodes.node_id" \
177 " LEFT JOIN nodegroup_nodes USING (nodegroup_id)"
179 if nodegroup_id_or_name_list:
180 # Separate the list into integers and strings
181 nodegroup_ids = filter(lambda nodegroup_id: isinstance(nodegroup_id, (int, long)),
182 nodegroup_id_or_name_list)
183 names = filter(lambda name: isinstance(name, StringTypes),
184 nodegroup_id_or_name_list)
185 sql += " WHERE (False"
187 sql += " OR nodegroup_id IN (%s)" % ", ".join(map(str, nodegroup_ids))
189 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names)).lower()
192 rows = self.api.db.selectall(sql)
194 if self.has_key(row['nodegroup_id']):
195 nodegroup = self[row['nodegroup_id']]
196 nodegroup.update(row)
198 self[row['nodegroup_id']] = NodeGroup(api, row)