- move common sync() functionality to Table.Row
[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.8 2006/10/02 18:32:31 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     table_name = 'nodes'
28     primary_key = 'node_id'
29     fields = {
30         'node_id': Parameter(int, "Node identifier"),
31         'hostname': Parameter(str, "Fully qualified hostname", max = 255),
32         'site_id': Parameter(int, "Site at which this node is located"),
33         'boot_state': Parameter(str, "Boot state", max = 20),
34         'model': Parameter(str, "Make and model of the actual machine", max = 255),
35         'boot_nonce': Parameter(str, "(Admin only) Random value generated by the node at last boot", max = 128),
36         'version': Parameter(str, "Apparent Boot CD version", max = 64),
37         'ssh_rsa_key': Parameter(str, "Last known SSH host key", max = 1024),
38         'date_created': Parameter(str, "Date and time when node entry was created", ro = True),
39         'last_updated': Parameter(str, "Date and time when node entry was created", ro = True),
40         'key': Parameter(str, "(Admin only) Node key", max = 256),
41         'session': Parameter(str, "(Admin only) Node session value", max = 256),
42         'nodenetwork_ids': Parameter([int], "List of network interfaces that this node has", ro = True),
43         'nodegroup_ids': Parameter([int], "List of node groups that this node is in", ro = True),
44         # 'conf_file_ids': Parameter([int], "List of configuration files specific to this node", ro = True),
45         # 'root_person_ids': Parameter([int], "(Admin only) List of people who have root access to this node", ro = True),
46         'slice_ids': Parameter([int], "List of slices on this node", ro = True),
47         # 'pcu_ids': Parameter([int], "List of PCUs that control this node", ro = True),
48         }
49
50     def __init__(self, api, fields):
51         Row.__init__(self, fields)
52         self.api = api
53
54     def validate_hostname(self, hostname):
55         # 1. Each part begins and ends with a letter or number.
56         # 2. Each part except the last can contain letters, numbers, or hyphens.
57         # 3. Each part is between 1 and 64 characters, including the trailing dot.
58         # 4. At least two parts.
59         # 5. Last part can only contain between 2 and 6 letters.
60         good_hostname = r'^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+' \
61                         r'[a-z]{2,6}$'
62         if not hostname or \
63            not re.match(good_hostname, hostname, re.IGNORECASE):
64             raise PLCInvalidArgument, "Invalid hostname"
65
66         conflicts = Nodes(self.api, [hostname])
67         for node_id, node in conflicts.iteritems():
68             if 'node_id' not in self or self['node_id'] != node_id:
69                 raise PLCInvalidArgument, "Hostname already in use"
70
71         # Check for conflicts with a nodenetwork hostname
72         conflicts = NodeNetworks(self.api, [hostname])
73         for nodenetwork_id in conflicts:
74             if 'nodenetwork_ids' not in self or nodenetwork_id not in self['nodenetwork_ids']:
75                 raise PLCInvalidArgument, "Hostname already in use"
76
77         return hostname
78
79     def validate_boot_state(self, boot_state):
80         if boot_state not in BootStates(self.api):
81             raise PLCInvalidArgument, "Invalid boot state"
82
83         return boot_state
84
85     def delete(self, commit = True):
86         """
87         Delete existing node.
88         """
89
90         assert 'node_id' in self
91
92         # Delete all nodenetworks
93         nodenetworks = NodeNetworks(self.api, self['nodenetwork_ids'])
94         for nodenetwork in nodenetworks.values():
95             nodenetwork.delete(commit = False)
96
97         # Clean up miscellaneous join tables
98         for table in ['nodegroup_node', 'slice_node', 'slice_attribute']:
99             self.api.db.do("DELETE FROM %s" \
100                            " WHERE node_id = %d" % \
101                            (table, self['node_id']))
102
103         # Mark as deleted
104         self['deleted'] = True
105         self.sync(commit)
106
107 class Nodes(Table):
108     """
109     Representation of row(s) from the nodes table in the
110     database.
111     """
112
113     def __init__(self, api, node_id_or_hostname_list = None):
114         self.api = api
115
116         sql = "SELECT %s FROM view_nodes WHERE deleted IS False" % \
117               ", ".join(Node.fields)
118
119         if node_id_or_hostname_list:
120             # Separate the list into integers and strings
121             node_ids = filter(lambda node_id: isinstance(node_id, (int, long)),
122                               node_id_or_hostname_list)
123             hostnames = filter(lambda hostname: isinstance(hostname, StringTypes),
124                                node_id_or_hostname_list)
125             sql += " AND (False"
126             if node_ids:
127                 sql += " OR node_id IN (%s)" % ", ".join(map(str, node_ids))
128             if hostnames:
129                 sql += " OR hostname IN (%s)" % ", ".join(api.db.quote(hostnames)).lower()
130             sql += ")"
131
132         rows = self.api.db.selectall(sql)
133
134         for row in rows:
135             self[row['node_id']] = node = Node(api, row)
136             for aggregate in ['nodenetwork_ids', 'nodegroup_ids',
137                               'conf_file_ids', 'root_person_ids', 'slice_ids',
138                               'pcu_ids']:
139                 if not node.has_key(aggregate) or node[aggregate] is None:
140                     node[aggregate] = []
141                 else:
142                     node[aggregate] = map(int, node[aggregate].split(','))