merge changes from HEAD
[plcapi.git] / PLC / Methods / UpdateNode.py
1 from PLC.Faults import *
2 from PLC.Method import Method
3 from PLC.Parameter import Parameter, Mixed
4 from PLC.Nodes import Node, Nodes
5 from PLC.Auth import Auth
6
7 can_update = lambda (field, value): field in \
8              ['hostname', 'boot_state', 'model', 'version',
9               'key', 'session', 'boot_nonce']
10
11 class UpdateNode(Method):
12     """
13     Updates a node. Only the fields specified in node_fields are
14     updated, all other fields are left untouched.
15     
16     PIs and techs can update only the nodes at their sites. Only
17     admins can update the key, session, and boot_nonce fields.
18
19     Returns 1 if successful, faults otherwise.
20     """
21
22     roles = ['admin', 'pi', 'tech']
23
24     node_fields = dict(filter(can_update, Node.fields.items()))
25
26     accepts = [
27         Auth(),
28         Mixed(Node.fields['node_id'],
29               Node.fields['hostname']),
30         node_fields
31         ]
32
33     returns = Parameter(int, '1 if successful')
34
35     def call(self, auth, node_id_or_hostname, node_fields):
36         node_fields = dict(filter(can_update, node_fields.items()))
37
38         # Remove admin only fields
39         if 'admin' not in self.caller['roles']:
40             for key in 'key', 'session', 'boot_nonce':
41                 if node_fields.has_key(key):
42                     del node_fields[key]
43
44         # Get account information
45         nodes = Nodes(self.api, [node_id_or_hostname])
46         if not nodes:
47             raise PLCInvalidArgument, "No such node"
48         node = nodes[0]
49
50         if node['peer_id'] is not None:
51             raise PLCInvalidArgument, "Not a local node"
52
53         # Authenticated function
54         assert self.caller is not None
55
56         # If we are not an admin, make sure that the caller is a
57         # member of the site at which the node is located.
58         if 'admin' not in self.caller['roles']:
59             if node['site_id'] not in self.caller['site_ids']:
60                 raise PLCPermissionDenied, "Not allowed to delete nodes from specified site"
61
62         node.update(node_fields)
63         node.update_last_updated(False)
64         node.sync()
65         
66         # Logging variables
67         self.event_objects = {'Node': [node['node_id']]}
68         self.message = 'Node %d updated: %s.' % \
69                 (node['node_id'], ", ".join(node_fields.keys()))
70         if 'boot_state' in node_fields.keys():
71                 self.message += ' boot_state updated to %s' %  node_fields['boot_state']
72
73         return 1