Merge remote-tracking branch 'origin/pycurl' into planetlab-4_0-branch
[plcapi.git] / trunk / PLC / Methods / AddNodeNetwork.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.NodeNetworks import NodeNetwork, NodeNetworks
6 from PLC.Auth import Auth
7
8 can_update = lambda (field, value): field not in ['nodenetwork_id', 'node_id']
9
10 class AddNodeNetwork(Method):
11     """
12
13     Adds a new network for a node. Any values specified in
14     nodenetwork_fields are used, otherwise defaults are
15     used. Acceptable values for method may be retrieved via
16     GetNetworkMethods. Acceptable values for type may be retrieved via
17     GetNetworkTypes.
18
19     If type is static, ip, gateway, network, broadcast, netmask, and
20     dns1 must all be specified in nodenetwork_fields. If type is dhcp,
21     these parameters, even if specified, are ignored.
22
23     PIs and techs may only add networks to their own nodes. Admins may
24     add networks to any node.
25
26     Returns the new nodenetwork_id (> 0) if successful, faults otherwise.
27     """
28
29     roles = ['admin', 'pi', 'tech']
30
31     nodenetwork_fields = dict(filter(can_update, NodeNetwork.fields.items()))
32
33     accepts = [
34         Auth(),
35         Mixed(Node.fields['node_id'],
36               Node.fields['hostname']),
37         nodenetwork_fields
38         ]
39
40     returns = Parameter(int, 'New nodenetwork_id (> 0) if successful')
41
42     
43     def call(self, auth, node_id_or_hostname, nodenetwork_fields):
44         nodenetwork_fields = dict(filter(can_update, nodenetwork_fields.items()))
45
46         # Check if node exists
47         nodes = Nodes(self.api, [node_id_or_hostname])
48         if not nodes:
49             raise PLCInvalidArgument, "No such node"
50         node = nodes[0]
51
52         # Authenticated function
53         assert self.caller is not None
54
55         # If we are not an admin, make sure that the caller is a
56         # member of the site where the node exists.
57         if 'admin' not in self.caller['roles']:
58             if node['site_id'] not in self.caller['site_ids']:
59                 raise PLCPermissionDenied, "Not allowed to add node network for specified node"
60
61         # Add node network
62         nodenetwork = NodeNetwork(self.api, nodenetwork_fields)
63         nodenetwork['node_id'] = node['node_id']
64         # if this is the first node network, make it primary
65         if not node['nodenetwork_ids']:
66                 nodenetwork['is_primary'] = True
67         nodenetwork.sync()
68         
69         # Logging variables
70         self.object_ids = [node['node_id'], nodenetwork['nodenetwork_id']]      
71         self.messgage = "Node network %d added" % nodenetwork['nodenetwork_id']
72
73         return nodenetwork['nodenetwork_id']