- add add_node() function to add node to this node group
[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.1 2006/09/06 15:36:07 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 existing node to specified 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     def flush(self, commit = True):
67         """
68         Flush changes back to the database.
69         """
70
71         self.validate()
72
73         # Fetch a new nodegroup_id if necessary
74         if 'nodegroup_id' not in self:
75             rows = self.api.db.selectall("SELECT NEXTVAL('nodegroups_nodegroup_id_seq') AS nodegroup_id")
76             if not rows:
77                 raise PLCDBError, "Unable to fetch new nodegroup_id"
78             self['nodegroup_id'] = rows[0]['nodegroup_id']
79             insert = True
80         else:
81             insert = False
82
83         # Filter out fields that cannot be set or updated directly
84         fields = dict(filter(lambda (key, value): key in self.fields,
85                              self.items()))
86
87         # Parameterize for safety
88         keys = fields.keys()
89         values = [self.api.db.param(key, value) for (key, value) in fields.items()]
90
91         if insert:
92             # Insert new row in nodegroups table
93             sql = "INSERT INTO nodegroups (%s) VALUES (%s)" % \
94                   (", ".join(keys), ", ".join(values))
95         else:
96             # Update existing row in sites table
97             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
98             sql = "UPDATE nodegroups SET " + \
99                   ", ".join(columns) + \
100                   " WHERE nodegroup_id = %(nodegroup_id)d"
101
102         self.api.db.do(sql, fields)
103
104         if commit:
105             self.api.db.commit()
106
107     def delete(self, commit = True):
108         """
109         Delete existing nodegroup from the database.
110         """
111
112         assert 'nodegroup_id' in self
113
114         # Delete ourself
115         tables = ['nodegroup_nodes', 'override_bootscripts',
116                   'conf_assoc', 'node_root_access']
117
118         if self['is_custom']:
119             tables.append('nodegroups')
120         else:
121             # XXX Cannot delete site node groups yet
122             pass
123
124         for table in tables:
125             self.api.db.do("DELETE FROM %s" \
126                            " WHERE nodegroup_id = %(nodegroup_id)" % \
127                            table, self)
128
129         if commit:
130             self.api.db.commit()
131
132 class NodeGroups(Table):
133     """
134     Representation of row(s) from the nodegroups table in the
135     database.
136     """
137
138     def __init__(self, api, nodegroup_id_or_name_list = None):
139         self.api = api
140
141         # N.B.: Node IDs returned may be deleted.
142         sql = "SELECT nodegroups.*, nodegroup_nodes.node_id" \
143               " FROM nodegroups" \
144               " LEFT JOIN nodegroup_nodes USING (nodegroup_id)"
145
146         if nodegroup_id_or_name_list:
147             # Separate the list into integers and strings
148             nodegroup_ids = filter(lambda nodegroup_id: isinstance(nodegroup_id, (int, long)),
149                                    nodegroup_id_or_name_list)
150             names = filter(lambda name: isinstance(name, StringTypes),
151                            nodegroup_id_or_name_list)
152             sql += " WHERE (False"
153             if nodegroup_ids:
154                 sql += " OR nodegroup_id IN (%s)" % ", ".join(map(str, nodegroup_ids))
155             if names:
156                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names)).lower()
157             sql += ")"
158
159         rows = self.api.db.selectall(sql)
160         for row in rows:
161             if self.has_key(row['nodegroup_id']):
162                 nodegroup = self[row['nodegroup_id']]
163                 nodegroup.update(row)
164             else:
165                 self[row['nodegroup_id']] = NodeGroup(api, row)