4589d513a7a4570e77d89eb032e288b970939c66
[plcapi.git] / PLC / Methods / BootUpdateNode.py
1 # $Id$
2 from PLC.Faults import *
3 from PLC.Method import Method
4 from PLC.Parameter import Parameter, Mixed
5 from PLC.Auth import Auth, BootAuth, SessionAuth
6 from PLC.Nodes import Node, Nodes
7 from PLC.Interfaces import Interface, Interfaces
8
9 can_update = lambda (field, value): field in \
10              ['method', 'mac', 'gateway', 'network',
11               'broadcast', 'netmask', 'dns1', 'dns2']
12
13 class BootUpdateNode(Method):
14     """
15     Allows the calling node to update its own record. Only the primary
16     network can be updated, and the node IP cannot be changed.
17
18     Returns 1 if updated successfully.
19     """
20
21     roles = ['node']
22
23     interface_fields = dict(filter(can_update, Interface.fields.items()))
24
25     accepts = [
26         Mixed(BootAuth(), SessionAuth()),
27         {'boot_state': Node.fields['boot_state'],
28          'primary_network': interface_fields,
29          'ssh_host_key': Node.fields['ssh_rsa_key']}
30         ]
31
32     returns = Parameter(int, '1 if successful')
33
34     def call(self, auth, node_fields):
35         # Update node state
36         if node_fields.has_key('boot_state'):
37             self.caller['boot_state'] = node_fields['boot_state']
38         if node_fields.has_key('ssh_host_key'):
39             self.caller['ssh_rsa_key'] = node_fields['ssh_host_key']
40
41         # Update primary interface state
42         if node_fields.has_key('primary_network'):
43             primary_network = node_fields['primary_network'] 
44
45             if 'interface_id' not in primary_network:
46                 raise PLCInvalidArgument, "Interface not specified"
47             if primary_network['interface_id'] not in self.caller['interface_ids']:
48                 raise PLCInvalidArgument, "Interface not associated with calling node"
49
50             interfaces = Interfaces(self.api, [primary_network['interface_id']])
51             if not interfaces:
52                 raise PLCInvalidArgument, "No such interface %r"%interface_id
53             interface = interfaces[0]
54
55             if not interface['is_primary']:
56                 raise PLCInvalidArgument, "Not the primary interface on record"
57
58             interface_fields = dict(filter(can_update, primary_network.items()))
59             interface.update(interface_fields)
60             interface.sync(commit = False)
61
62         # indicate that node has booted & contacted PLC.
63         if isinstance(self.caller, Node):
64             node = self.caller
65             node.update_last_contact()
66
67         self.caller.sync(commit = True)
68         self.message = "Node updated: %s" % ", ".join(node_fields.keys())
69
70         return 1