add validation
[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.2 2006/09/06 16:03: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     def __init__(self, api, fields):
39         Row.__init__(self, fields)
40         self.api = api
41
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"
47
48     def add_node(self, node, commit = True):
49         """
50         Add node to existing nodegroup.
51         """
52
53         assert 'nodegroup_id' in self
54         assert isinstance(node, Node)
55         assert 'node_id' in node
56
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)",
61                        locals())
62
63         if commit:
64             self.api.db.commit()
65
66         if 'node_ids' in self and node_id not in self['node_ids']:
67             self['node_ids'].append(node_id)
68
69         if 'nodegroup_ids' in node and nodegroup_id not in node['nodegroup_ids']:
70             node['nodegroup_ids'].append(nodegroup_id)
71
72     def remove_node(self, node, commit = True):
73         """
74         Remove node from existing nodegroup.
75         """
76
77         assert 'nodegroup_id' in self
78         assert isinstance(node, Node)
79         assert 'node_id' in node
80
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)",
85                        locals())
86
87         if commit:
88             self.api.db.commit()
89
90         if 'node_ids' in self and node_id not in self['node_ids']:
91             self['node_ids'].append(node_id)
92
93         if 'nodegroup_ids' in node and nodegroup_id not in node['nodegroup_ids']:
94             node['nodegroup_ids'].append(nodegroup_id)
95
96     def flush(self, commit = True):
97         """
98         Flush changes back to the database.
99         """
100
101         self.validate()
102
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")
106             if not rows:
107                 raise PLCDBError, "Unable to fetch new nodegroup_id"
108             self['nodegroup_id'] = rows[0]['nodegroup_id']
109             insert = True
110         else:
111             insert = False
112
113         # Filter out fields that cannot be set or updated directly
114         fields = dict(filter(lambda (key, value): key in self.fields,
115                              self.items()))
116
117         # Parameterize for safety
118         keys = fields.keys()
119         values = [self.api.db.param(key, value) for (key, value) in fields.items()]
120
121         if insert:
122             # Insert new row in nodegroups table
123             sql = "INSERT INTO nodegroups (%s) VALUES (%s)" % \
124                   (", ".join(keys), ", ".join(values))
125         else:
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"
131
132         self.api.db.do(sql, fields)
133
134         if commit:
135             self.api.db.commit()
136
137     def delete(self, commit = True):
138         """
139         Delete existing nodegroup from the database.
140         """
141
142         assert 'nodegroup_id' in self
143
144         # Delete ourself
145         tables = ['nodegroup_nodes', 'override_bootscripts',
146                   'conf_assoc', 'node_root_access']
147
148         if self['is_custom']:
149             tables.append('nodegroups')
150         else:
151             # XXX Cannot delete site node groups yet
152             pass
153
154         for table in tables:
155             self.api.db.do("DELETE FROM %s" \
156                            " WHERE nodegroup_id = %(nodegroup_id)" % \
157                            table, self)
158
159         if commit:
160             self.api.db.commit()
161
162 class NodeGroups(Table):
163     """
164     Representation of row(s) from the nodegroups table in the
165     database.
166     """
167
168     def __init__(self, api, nodegroup_id_or_name_list = None):
169         self.api = api
170
171         # N.B.: Node IDs returned may be deleted.
172         sql = "SELECT nodegroups.*, nodegroup_nodes.node_id" \
173               " FROM nodegroups" \
174               " LEFT JOIN nodegroup_nodes USING (nodegroup_id)"
175
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"
183             if nodegroup_ids:
184                 sql += " OR nodegroup_id IN (%s)" % ", ".join(map(str, nodegroup_ids))
185             if names:
186                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names)).lower()
187             sql += ")"
188
189         rows = self.api.db.selectall(sql)
190         for row in rows:
191             if self.has_key(row['nodegroup_id']):
192                 nodegroup = self[row['nodegroup_id']]
193                 nodegroup.update(row)
194             else:
195                 self[row['nodegroup_id']] = NodeGroup(api, row)