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