- added class variables: event_type, object_type, object_ids (used by event logger)
[plcapi.git] / 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 PasswordAuth
7
8 can_update = lambda (field, value): field in \
9              ['ip', 'mac', 'gateway', 'network', 'broadcast', 'netmask',
10               'dns1', 'dns2', 'hostname', 'bwlimit', 'is_primary']
11
12 class AddNodeNetwork(Method):
13     """
14     Adds a new network for a node. Any values specified in
15     nodenetwork_fields are used, otherwise defaults are used. Acceptable
16     values for method are dhcp, static, proxy, tap, and
17     ipmi. Acceptable value for type is ipv4. If type is static, ip,
18     gateway, network, broadcast, netmask, and dns1 must all be
19     specified in nodenetwork_fields. If type is dhcp, these parameters,
20     even if specified, are ignored.
21
22     PIs and techs may only add networks to their own nodes. ins may
23     add networks to any node.
24
25     Returns the new nodenetwork_id (> 0) if successful, faults otherwise.
26     """
27
28     roles = ['admin', 'pi', 'tech']
29
30     update_fields = dict(filter(can_update, NodeNetwork.fields.items()))
31
32     accepts = [
33         PasswordAuth(),
34         Node.fields['node_id'],
35         NodeNetwork.fields['method'],
36         NodeNetwork.fields['type'],
37         update_fields
38         ]
39
40     returns = Parameter(int, 'New nodenetwork_id (> 0) if successful')
41
42     event_type = 'Add'
43     object_type = 'NodeNetwork'
44     object_ids = []
45
46     def call(self, auth, node_id, method, type, nodenetwork_fields = {}):
47         nodenetwork_fields = dict(filter(can_update, nodenetwork_fields.items()))
48
49         # Check if node exists
50         nodes = Nodes(self.api, [node_id]).values()
51         if not nodes:
52             raise PLCInvalidArgument, "No such node"
53         node = nodes[0]
54
55         # Authenticated function
56         assert self.caller is not None
57
58         # If we are not an admin, make sure that the caller is a
59         # member of the site where the node exists.
60         if 'admin' not in self.caller['roles']:
61             if node['site_id'] not in self.caller['site_ids']:
62                 raise PLCPermissionDenied, "Not allowed to add node network for specified node"
63
64         # Add node network
65         nodenetwork = NodeNetwork(self.api, nodenetwork_fields)
66         nodenetwork['node_id'] = node_id
67         nodenetwork['method'] = method
68         nodenetwork['type'] = type
69         nodenetwork.sync()
70         self.object_ids = [nodenetwork['nodenetwork_id']]       
71
72         return nodenetwork['nodenetwork_id']