7930ab103f45eba4bb8d517ed99cf7258de1b207
[plcapi.git] / PLC / Nodes.py
1 #
2 # Functions for interacting with the nodes table in the database
3 #
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
6 #
7 # $Id: Nodes.py,v 1.7 2006/10/02 16:04:42 mlhuang Exp $
8 #
9
10 from types import StringTypes
11 import re
12
13 from PLC.Faults import *
14 from PLC.Parameter import Parameter
15 from PLC.Debug import profile
16 from PLC.Table import Row, Table
17 from PLC.NodeNetworks import NodeNetwork, NodeNetworks
18 from PLC.BootStates import BootStates
19
20 class Node(Row):
21     """
22     Representation of a row in the nodes table. To use, optionally
23     instantiate with a dict of values. Update as you would a
24     dict. Commit to the database with sync().
25     """
26
27     fields = {
28         'node_id': Parameter(int, "Node identifier"),
29         'hostname': Parameter(str, "Fully qualified hostname", max = 255),
30         'site_id': Parameter(int, "Site at which this node is located"),
31         'boot_state': Parameter(str, "Boot state", max = 20),
32         'model': Parameter(str, "Make and model of the actual machine", max = 255),
33         'boot_nonce': Parameter(str, "(Admin only) Random value generated by the node at last boot", max = 128),
34         'version': Parameter(str, "Apparent Boot CD version", max = 64),
35         'ssh_rsa_key': Parameter(str, "Last known SSH host key", max = 1024),
36         'date_created': Parameter(str, "Date and time when node entry was created", ro = True),
37         'last_updated': Parameter(str, "Date and time when node entry was created", ro = True),
38         'key': Parameter(str, "(Admin only) Node key", max = 256),
39         'session': Parameter(str, "(Admin only) Node session value", max = 256),
40         'nodenetwork_ids': Parameter([int], "List of network interfaces that this node has", ro = True),
41         'nodegroup_ids': Parameter([int], "List of node groups that this node is in", ro = True),
42         # 'conf_file_ids': Parameter([int], "List of configuration files specific to this node", ro = True),
43         # 'root_person_ids': Parameter([int], "(Admin only) List of people who have root access to this node", ro = True),
44         'slice_ids': Parameter([int], "List of slices on this node", ro = True),
45         # 'pcu_ids': Parameter([int], "List of PCUs that control this node", ro = True),
46         }
47
48     def __init__(self, api, fields):
49         Row.__init__(self, fields)
50         self.api = api
51
52     def validate_hostname(self, hostname):
53         # 1. Each part begins and ends with a letter or number.
54         # 2. Each part except the last can contain letters, numbers, or hyphens.
55         # 3. Each part is between 1 and 64 characters, including the trailing dot.
56         # 4. At least two parts.
57         # 5. Last part can only contain between 2 and 6 letters.
58         good_hostname = r'^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+' \
59                         r'[a-z]{2,6}$'
60         if not hostname or \
61            not re.match(good_hostname, hostname, re.IGNORECASE):
62             raise PLCInvalidArgument, "Invalid hostname"
63
64         conflicts = Nodes(self.api, [hostname])
65         for node_id, node in conflicts.iteritems():
66             if 'node_id' not in self or self['node_id'] != node_id:
67                 raise PLCInvalidArgument, "Hostname already in use"
68
69         # Check for conflicts with a nodenetwork hostname
70         conflicts = NodeNetworks(self.api, [hostname])
71         for nodenetwork_id in conflicts:
72             if 'nodenetwork_ids' not in self or nodenetwork_id not in self['nodenetwork_ids']:
73                 raise PLCInvalidArgument, "Hostname already in use"
74
75         return hostname
76
77     def validate_boot_state(self, boot_state):
78         if boot_state not in BootStates(self.api):
79             raise PLCInvalidArgument, "Invalid boot state"
80
81         return boot_state
82
83     def sync(self, commit = True):
84         """
85         Flush changes back to the database.
86         """
87
88         self.validate()
89
90         # Fetch a new node_id if necessary
91         if 'node_id' not in self:
92             rows = self.api.db.selectall("SELECT NEXTVAL('nodes_node_id_seq') AS node_id")
93             if not rows:
94                 raise PLCDBError, "Unable to fetch new node_id"
95             self['node_id'] = rows[0]['node_id']
96             insert = True
97         else:
98             insert = False
99
100         # Filter out fields that cannot be set or updated directly
101         nodes_fields = self.api.db.fields('nodes')
102         fields = dict(filter(lambda (key, value): \
103                              key in nodes_fields and \
104                              (key not in self.fields or not self.fields[key].ro),
105                              self.items()))
106
107         # Parameterize for safety
108         keys = fields.keys()
109         values = [self.api.db.param(key, value) for (key, value) in fields.items()]
110
111         if insert:
112             # Insert new row in nodes table
113             sql = "INSERT INTO nodes (%s) VALUES (%s)" % \
114                   (", ".join(keys), ", ".join(values))
115         else:
116             # Update existing row in nodes table
117             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
118             sql = "UPDATE nodes SET " + \
119                   ", ".join(columns) + \
120                   " WHERE node_id = %(node_id)d"
121
122         self.api.db.do(sql, fields)
123
124         if commit:
125             self.api.db.commit()
126
127     def delete(self, commit = True):
128         """
129         Delete existing node.
130         """
131
132         assert 'node_id' in self
133
134         # Delete all nodenetworks
135         nodenetworks = NodeNetworks(self.api, self['nodenetwork_ids'])
136         for nodenetwork in nodenetworks.values():
137             nodenetwork.delete(commit = False)
138
139         # Clean up miscellaneous join tables
140         for table in ['nodegroup_node', 'slice_node', 'slice_attribute']:
141             self.api.db.do("DELETE FROM %s" \
142                            " WHERE node_id = %d" % \
143                            (table, self['node_id']))
144
145         # Mark as deleted
146         self['deleted'] = True
147         self.sync(commit)
148
149 class Nodes(Table):
150     """
151     Representation of row(s) from the nodes table in the
152     database.
153     """
154
155     def __init__(self, api, node_id_or_hostname_list = None, fields = Node.fields.keys()):
156         self.api = api
157
158         sql = "SELECT %s FROM view_nodes WHERE deleted IS False" % \
159               ", ".join(fields)
160
161         if node_id_or_hostname_list:
162             # Separate the list into integers and strings
163             node_ids = filter(lambda node_id: isinstance(node_id, (int, long)),
164                               node_id_or_hostname_list)
165             hostnames = filter(lambda hostname: isinstance(hostname, StringTypes),
166                                node_id_or_hostname_list)
167             sql += " AND (False"
168             if node_ids:
169                 sql += " OR node_id IN (%s)" % ", ".join(map(str, node_ids))
170             if hostnames:
171                 sql += " OR hostname IN (%s)" % ", ".join(api.db.quote(hostnames)).lower()
172             sql += ")"
173
174         rows = self.api.db.selectall(sql)
175
176         for row in rows:
177             self[row['node_id']] = node = Node(api, row)
178             for aggregate in ['nodenetwork_ids', 'nodegroup_ids',
179                               'conf_file_ids', 'root_person_ids', 'slice_ids',
180                               'pcu_ids']:
181                 if not node.has_key(aggregate) or node[aggregate] is None:
182                     node[aggregate] = []
183                 else:
184                     node[aggregate] = map(int, node[aggregate].split(','))