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