- node group names are case sensitive
[plcapi.git] / PLC / NodeGroups.py
1 #
2 # Functions for interacting with the nodegroups table in the database
3 #
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
6 #
7 # $Id: NodeGroups.py,v 1.8 2006/09/19 19:08:24 mlhuang Exp $
8 #
9
10 from types import StringTypes
11
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
17
18 class NodeGroup(Row):
19     """
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().
23     """
24
25     fields = {
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)")
30         }
31
32     # These fields are derived from join tables and are not
33     # actually in the nodegroups table.
34     join_fields = {
35         'node_ids': Parameter([int], "List of nodes in this node group"),
36         }
37
38     all_fields = dict(fields.items() + join_fields.items())
39
40     def __init__(self, api, fields):
41         Row.__init__(self, fields)
42         self.api = api
43
44     def validate_name(self, name):
45         #remove leading and trailing spaces
46         name = name.strip()
47
48         #make sure name is not blank after we removed the spaces
49         if not len(name) > 0:
50                 raise PLCInvalidArgument, "Invalid Node Group Name"
51         
52         #make sure name doenst alredy exist
53         conflicts = NodeGroups(self.api, [name])
54         for nodegroup_id in conflicts:
55             if 'nodegroup_id' not in self or self['nodegroup_id'] != nodegroup_id:
56                raise PLCInvalidArgument, "Node group name already in use"
57
58         return name
59         
60     def validate_description(self, description):
61         #remove trailing and leading spaces
62         description = description.strip()
63         
64         #make sure decription is not blank after we removed the spaces  
65         if not len(description) > 0:
66                 raise PLCInvalidArgument, "Invalid Node Group Description"
67
68         return description
69
70     def add_node(self, node, commit = True):
71         """
72         Add node to existing nodegroup.
73         """
74
75         assert 'nodegroup_id' in self
76         assert isinstance(node, Node)
77         assert 'node_id' in node
78
79         node_id = node['node_id']
80         nodegroup_id = self['nodegroup_id']
81         self.api.db.do("INSERT INTO nodegroup_nodes (nodegroup_id, node_id)" \
82                        " VALUES(%(nodegroup_id)d, %(node_id)d)",
83                        locals())
84
85         if commit:
86             self.api.db.commit()
87
88         if 'node_ids' in self and node_id not in self['node_ids']:
89             self['node_ids'].append(node_id)
90
91         if 'nodegroup_ids' in node and nodegroup_id not in node['nodegroup_ids']:
92             node['nodegroup_ids'].append(nodegroup_id)
93
94     def remove_node(self, node, commit = True):
95         """
96         Remove node from existing nodegroup.
97         """
98
99         assert 'nodegroup_id' in self
100         assert isinstance(node, Node)
101         assert 'node_id' in node
102
103         node_id = node['node_id']
104         nodegroup_id = self['nodegroup_id']
105         self.api.db.do("INSERT INTO nodegroup_nodes (nodegroup_id, node_id)" \
106                        " VALUES(%(nodegroup_id)d, %(node_id)d)",
107                        locals())
108
109         if commit:
110             self.api.db.commit()
111
112         if 'node_ids' in self and node_id not in self['node_ids']:
113             self['node_ids'].append(node_id)
114
115         if 'nodegroup_ids' in node and nodegroup_id not in node['nodegroup_ids']:
116             node['nodegroup_ids'].append(nodegroup_id)
117
118     def flush(self, commit = True):
119         """
120         Flush changes back to the database.
121         """
122
123         self.validate()
124
125         # Fetch a new nodegroup_id if necessary
126         if 'nodegroup_id' not in self:
127             rows = self.api.db.selectall("SELECT NEXTVAL('nodegroups_nodegroup_id_seq') AS nodegroup_id")
128             if not rows:
129                 raise PLCDBError, "Unable to fetch new nodegroup_id"
130             self['nodegroup_id'] = rows[0]['nodegroup_id']
131             insert = True
132         else:
133             insert = False
134
135         # Filter out fields that cannot be set or updated directly
136         fields = dict(filter(lambda (key, value): key in self.fields,
137                              self.items()))
138
139         # Parameterize for safety
140         keys = fields.keys()
141         values = [self.api.db.param(key, value) for (key, value) in fields.items()]
142
143         if insert:
144             # Insert new row in nodegroups table
145             sql = "INSERT INTO nodegroups (%s) VALUES (%s)" % \
146                   (", ".join(keys), ", ".join(values))
147         else:
148             # Update existing row in nodegroups table
149             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
150             sql = "UPDATE nodegroups SET " + \
151                   ", ".join(columns) + \
152                   " WHERE nodegroup_id = %(nodegroup_id)d"
153
154         self.api.db.do(sql, fields)
155
156         if commit:
157             self.api.db.commit()
158             
159
160     def delete(self, commit = True):
161         """
162         Delete existing nodegroup from the database.
163         """
164
165         assert 'nodegroup_id' in self
166         assert self is not {}
167         # Delete ourself
168         tables = ['nodegroup_nodes', 'override_bootscripts',
169                   'conf_assoc', 'node_root_access']
170
171         if self['is_custom']:
172             tables.append('nodegroups')
173         else:
174             # XXX Cannot delete site node groups yet
175             pass
176
177         for table in tables:
178             self.api.db.do("DELETE FROM %s" \
179                            " WHERE nodegroup_id = %d" % \
180                            (table, self['nodegroup_id']), self)
181
182         if commit:
183             self.api.db.commit()
184
185 class NodeGroups(Table):
186     """
187     Representation of row(s) from the nodegroups table in the
188     database.
189     """
190
191     def __init__(self, api, nodegroup_id_or_name_list = None):
192         self.api = api
193
194         # N.B.: Node IDs returned may be deleted.
195         sql = "SELECT nodegroups.*, nodegroup_nodes.node_id" \
196               " FROM nodegroups" \
197               " LEFT JOIN nodegroup_nodes USING (nodegroup_id)"
198
199         if nodegroup_id_or_name_list:
200             # Separate the list into integers and strings
201             nodegroup_ids = filter(lambda nodegroup_id: isinstance(nodegroup_id, (int, long)),
202                                    nodegroup_id_or_name_list)
203             names = filter(lambda name: isinstance(name, StringTypes),
204                            nodegroup_id_or_name_list)
205             sql += " WHERE (False"
206             if nodegroup_ids:
207                 sql += " OR nodegroup_id IN (%s)" % ", ".join(map(str, nodegroup_ids))
208             if names:
209                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
210             sql += ")"
211
212         rows = self.api.db.selectall(sql)
213         for row in rows:
214             if self.has_key(row['nodegroup_id']):
215                 nodegroup = self[row['nodegroup_id']]
216                 nodegroup.update(row)
217             else:
218                 self[row['nodegroup_id']] = NodeGroup(api, row)