remove old Shell.py implementation (moved to plcsh and PLC/Shell.py)
[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.28 2006/12/05 16:45:03 thierry 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.Filter import Filter
16 from PLC.Debug import profile
17 from PLC.Table import Row, Table
18 from PLC.NodeNetworks import NodeNetwork, NodeNetworks
19 from PLC.BootStates import BootStates
20
21 def valid_hostname(hostname):
22     # 1. Each part begins and ends with a letter or number.
23     # 2. Each part except the last can contain letters, numbers, or hyphens.
24     # 3. Each part is between 1 and 64 characters, including the trailing dot.
25     # 4. At least two parts.
26     # 5. Last part can only contain between 2 and 6 letters.
27     good_hostname = r'^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+' \
28                     r'[a-z]{2,6}$'
29     return hostname and \
30            re.match(good_hostname, hostname, re.IGNORECASE)
31
32 class Node(Row):
33     """
34     Representation of a row in the nodes table. To use, optionally
35     instantiate with a dict of values. Update as you would a
36     dict. Commit to the database with sync().
37     """
38
39     table_name = 'nodes'
40     primary_key = 'node_id'
41     join_tables = ['nodegroup_node', 'conf_file_node', 'nodenetworks', 'pcu_node', 'slice_node', 'slice_attribute', 'node_session', 'peer_node']
42     fields = {
43         'node_id': Parameter(int, "Node identifier"),
44         'hostname': Parameter(str, "Fully qualified hostname", max = 255),
45         'site_id': Parameter(int, "Site at which this node is located"),
46         'boot_state': Parameter(str, "Boot state", max = 20),
47         'model': Parameter(str, "Make and model of the actual machine", max = 255, nullok = True),
48         'boot_nonce': Parameter(str, "(Admin only) Random value generated by the node at last boot", max = 128),
49         'version': Parameter(str, "Apparent Boot CD version", max = 64),
50         'ssh_rsa_key': Parameter(str, "Last known SSH host key", max = 1024),
51         'date_created': Parameter(int, "Date and time when node entry was created", ro = True),
52         'last_updated': Parameter(int, "Date and time when node entry was created", ro = True),
53         'key': Parameter(str, "(Admin only) Node key", max = 256),
54         'session': Parameter(str, "(Admin only) Node session value", max = 256, ro = True),
55         'nodenetwork_ids': Parameter([int], "List of network interfaces that this node has"),
56         'nodegroup_ids': Parameter([int], "List of node groups that this node is in"),
57         'conf_file_ids': Parameter([int], "List of configuration files specific to this node"),
58         # 'root_person_ids': Parameter([int], "(Admin only) List of people who have root access to this node"),
59         'slice_ids': Parameter([int], "List of slices on this node"),
60         'pcu_ids': Parameter([int], "List of PCUs that control this node"),
61         'ports': Parameter([int], "List of PCU ports that this node is connected to"),
62         'peer_id': Parameter(int, "Peer to which this node belongs", nullok = True),
63         'peer_node_id': Parameter(int, "Foreign node identifier at peer", nullok = True),
64         }
65
66     # for Cache
67     class_key = 'hostname'
68     foreign_fields = ['boot_state','model','version']
69     # forget about these ones, they are read-only anyway
70     # handling them causes Cache to re-sync all over again 
71     # 'date_created','last_updated'
72     foreign_xrefs = [
73         # in this case, we dont need the 'table' but Cache will look it up, so...
74         {'field' : 'site_id' , 'class' : 'Site' , 'table' : 'unused-on-direct-refs' } ,
75         ]
76
77     def validate_hostname(self, hostname):
78         if not valid_hostname(hostname):
79             raise PLCInvalidArgument, "Invalid hostname"
80
81         conflicts = Nodes(self.api, [hostname])
82         for node in conflicts:
83             if 'node_id' not in self or self['node_id'] != node['node_id']:
84                 raise PLCInvalidArgument, "Hostname already in use"
85
86         return hostname
87
88     def validate_boot_state(self, boot_state):
89         boot_states = [row['boot_state'] for row in BootStates(self.api)]
90         if boot_state not in boot_states:
91             raise PLCInvalidArgument, "Invalid boot state"
92
93         return boot_state
94
95     validate_date_created = Row.validate_timestamp
96     validate_last_updated = Row.validate_timestamp
97
98     def delete(self, commit = True):
99         """
100         Delete existing node.
101         """
102
103         assert 'node_id' in self
104
105         # Clean up miscellaneous join tables
106         for table in self.join_tables:
107             self.api.db.do("DELETE FROM %s WHERE node_id = %d" % \
108                            (table, self['node_id']))
109
110         # Mark as deleted
111         self['deleted'] = True
112         self.sync(commit)
113
114
115 class Nodes(Table):
116     """
117     Representation of row(s) from the nodes table in the
118     database.
119     """
120
121     def __init__(self, api, node_filter = None, columns = None, peer_id = None):
122         Table.__init__(self, api, Node, columns)
123
124         sql = "SELECT %s FROM view_nodes WHERE deleted IS False" % \
125               ", ".join(self.columns)
126
127         if peer_id is None:
128             sql += " AND peer_id IS NULL"
129         elif isinstance(peer_id, (int, long)):
130             sql += " AND peer_id = %d" % peer_id
131
132         if node_filter is not None:
133             if isinstance(node_filter, (list, tuple, set)):
134                 # Separate the list into integers and strings
135                 ints = filter(lambda x: isinstance(x, (int, long)), node_filter)
136                 strs = filter(lambda x: isinstance(x, StringTypes), node_filter)
137                 node_filter = Filter(Node.fields, {'node_id': ints, 'hostname': strs})
138                 sql += " AND (%s)" % node_filter.sql(api, "OR")
139             elif isinstance(node_filter, dict):
140                 node_filter = Filter(Node.fields, node_filter)
141                 sql += " AND (%s)" % node_filter.sql(api, "AND")
142
143         self.selectall(sql)