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