- move common sync() functionality to Table.Row
[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.10 2006/09/25 14:52:01 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 sync().
23     """
24
25     table_name = 'nodegroups'
26     primary_key = 'nodegroup_id'
27     fields = {
28         'nodegroup_id': Parameter(int, "Node group identifier"),
29         'name': Parameter(str, "Node group name", max = 50),
30         'description': Parameter(str, "Node group description", max = 200),
31         'node_ids': Parameter([int], "List of nodes in this node group"),
32         }
33
34     def __init__(self, api, fields = {}):
35         Row.__init__(self, fields)
36         self.api = api
37
38     def validate_name(self, name):
39         # Remove leading and trailing spaces
40         name = name.strip()
41
42         # Make sure name is not blank after we removed the spaces
43         if not len(name) > 0:
44                 raise PLCInvalidArgument, "Invalid node group name"
45         
46         # Make sure node group does not alredy exist
47         conflicts = NodeGroups(self.api, [name])
48         for nodegroup_id in conflicts:
49             if 'nodegroup_id' not in self or self['nodegroup_id'] != nodegroup_id:
50                raise PLCInvalidArgument, "Node group name already in use"
51
52         return name
53
54     def add_node(self, node, commit = True):
55         """
56         Add node to existing nodegroup.
57         """
58
59         assert 'nodegroup_id' in self
60         assert isinstance(node, Node)
61         assert 'node_id' in node
62
63         node_id = node['node_id']
64         nodegroup_id = self['nodegroup_id']
65         self.api.db.do("INSERT INTO nodegroup_node (nodegroup_id, node_id)" \
66                        " VALUES(%(nodegroup_id)d, %(node_id)d)",
67                        locals())
68
69         if commit:
70             self.api.db.commit()
71
72         if 'node_ids' in self and node_id not in self['node_ids']:
73             self['node_ids'].append(node_id)
74
75         if 'nodegroup_ids' in node and nodegroup_id not in node['nodegroup_ids']:
76             node['nodegroup_ids'].append(nodegroup_id)
77
78     def remove_node(self, node, commit = True):
79         """
80         Remove node from existing nodegroup.
81         """
82
83         assert 'nodegroup_id' in self
84         assert isinstance(node, Node)
85         assert 'node_id' in node
86
87         node_id = node['node_id']
88         nodegroup_id = self['nodegroup_id']
89         self.api.db.do("DELETE FROM nodegroup_node" \
90                        " WHERE nodegroup_id = %(nodegroup_id)d" \
91                        " AND node_id = %(node_id)d",
92                        locals())
93
94         if commit:
95             self.api.db.commit()
96
97         if 'node_ids' in self and node_id in self['node_ids']:
98             self['node_ids'].remove(node_id)
99
100         if 'nodegroup_ids' in node and nodegroup_id in node['nodegroup_ids']:
101             node['nodegroup_ids'].remove(nodegroup_id)
102
103     def delete(self, commit = True):
104         """
105         Delete existing nodegroup from the database.
106         """
107
108         assert 'nodegroup_id' in self
109
110         # Clean up miscellaneous join tables
111         for table in ['nodegroup_node', 'nodegroups']:
112             self.api.db.do("DELETE FROM %s" \
113                            " WHERE nodegroup_id = %d" % \
114                            (table, self['nodegroup_id']), self)
115
116         if commit:
117             self.api.db.commit()
118
119 class NodeGroups(Table):
120     """
121     Representation of row(s) from the nodegroups table in the
122     database.
123     """
124
125     def __init__(self, api, nodegroup_id_or_name_list = None):
126         self.api = api
127
128         sql = "SELECT %s FROM view_nodegroups" % \
129               ", ".join(NodeGroup.fields)
130
131         if nodegroup_id_or_name_list:
132             # Separate the list into integers and strings
133             nodegroup_ids = filter(lambda nodegroup_id: isinstance(nodegroup_id, (int, long)),
134                                    nodegroup_id_or_name_list)
135             names = filter(lambda name: isinstance(name, StringTypes),
136                            nodegroup_id_or_name_list)
137             sql += " WHERE (False"
138             if nodegroup_ids:
139                 sql += " OR nodegroup_id IN (%s)" % ", ".join(map(str, nodegroup_ids))
140             if names:
141                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
142             sql += ")"
143
144         rows = self.api.db.selectall(sql)
145
146         for row in rows:
147             self[row['nodegroup_id']] = nodegroup = NodeGroup(api, row)
148             for aggregate in ['node_ids']:
149                 if not nodegroup.has_key(aggregate) or nodegroup[aggregate] is None:
150                     nodegroup[aggregate] = []
151                 else:
152                     nodegroup[aggregate] = map(int, nodegroup[aggregate].split(','))