1d5e505229f24cea57738ff6628d8261c302ae7a
[plcapi.git] / PLC / Methods / AddNodeToPCU.py
1 # $Id$
2 from PLC.Faults import *
3 from PLC.Method import Method
4 from PLC.Parameter import Parameter, Mixed
5 from PLC.Nodes import Node, Nodes
6 from PLC.PCUs import PCU, PCUs
7 from PLC.Sites import Site, Sites
8 from PLC.Auth import Auth
9
10 class AddNodeToPCU(Method):
11     """
12     Adds a node to a port on a PCU. Faults if the node has already
13     been added to the PCU or if the port is already in use.
14
15     Non-admins may only update PCUs at their sites.
16
17     Returns 1 if successful, faults otherwise.
18     """
19
20     roles = ['admin', 'pi', 'tech']
21
22     accepts = [
23         Auth(),
24         Mixed(Node.fields['node_id'],
25               Node.fields['hostname']),
26         PCU.fields['pcu_id'],
27         Parameter(int, 'PCU port number')
28         ]
29
30     returns = Parameter(int, '1 if successful')
31
32     def call(self, auth, node_id_or_hostname, pcu_id, port):
33          # Get node
34         nodes = Nodes(self.api, [node_id_or_hostname])
35         if not nodes:
36             raise PLCInvalidArgument, "No such node"
37         node = nodes[0]
38
39         if node['peer_id'] is not None:
40             raise PLCInvalidArgument, "Not a local node"
41
42         # Get PCU
43         pcus = PCUs(self.api, [pcu_id])
44         if not pcus:
45             raise PLCInvalidArgument, "No such PCU"
46         pcu = pcus[0]
47
48         if 'admin' not in self.caller['roles']:
49             ok = False
50             sites = Sites(self.api, self.caller['site_ids'])
51             for site in sites:
52                 if pcu['pcu_id'] in site['pcu_ids']:
53                     ok = True
54                     break
55             if not ok:
56                 raise PLCPermissionDenied, "Not allowed to update that PCU"
57         
58         # Add node to PCU
59         if node['node_id'] in pcu['node_ids']:
60             raise PLCInvalidArgument, "Node already controlled by PCU"
61
62         if node['site_id'] != pcu['site_id']:
63             raise PLCInvalidArgument, "Node is at a different site than this PCU"
64
65         if port in pcu['ports']:
66             raise PLCInvalidArgument, "PCU port already in use"
67
68         pcu.add_node(node, port)
69
70         # Logging variables
71         self.event_objects = {'Node': [node['node_id']],
72                               'PCU': [pcu['pcu_id']]}
73         self.message = 'Node %d added to pcu %d on port %d' % \
74                 (node['node_id'], pcu['pcu_id'], port)
75         return 1