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