- Change .py files to use 4-space indents and no hard tab characters.
[plcapi.git] / PLC / Methods / GetWhitelist.py
1 # $Id$
2 # $URL$
3 from PLC.Faults import *
4 from PLC.Method import Method
5 from PLC.Parameter import Parameter, Mixed
6 from PLC.Filter import Filter
7 from PLC.Nodes import Node, Nodes
8 from PLC.Persons import Person, Persons
9 from PLC.Auth import Auth
10
11 class GetWhitelist(Method):
12     """
13     Returns an array of structs containing details about the specified nodes
14     whitelists. If node_filter is specified and is an array of node identifiers or
15     hostnames, or a struct of node attributes, only nodes matching the
16     filter will be returned. If return_fields is specified, only the
17     specified details will be returned.
18
19     Some fields may only be viewed by admins.
20     """
21
22     roles = ['admin', 'pi', 'user', 'tech', 'node', 'anonymous']
23
24     accepts = [
25         Auth(),
26         Mixed([Mixed(Node.fields['node_id'],
27                      Node.fields['hostname'])],
28               Filter(Node.fields)),
29         Parameter([str], "List of fields to return", nullok = True),
30         ]
31
32     returns = [Node.fields]
33
34
35     def call(self, auth, node_filter = None, return_fields = None):
36
37         # Must query at least slice_ids_whitelist
38         if return_fields is not None:
39             added_fields = set(['slice_ids_whitelist']).difference(return_fields)
40             return_fields += added_fields
41         else:
42             added_fields =[]
43
44         # Get node information
45         nodes = Nodes(self.api, node_filter, return_fields)
46
47         # Remove all nodes without a whitelist
48         for node in nodes[:]:
49             if not node['slice_ids_whitelist']:
50                 nodes.remove(node)
51
52         # Remove admin only fields
53         if not isinstance(self.caller, Person) or \
54            'admin' not in self.caller['roles']:
55             slice_ids = set()
56             if self.caller:
57                 slice_ids.update(self.caller['slice_ids'])
58             #if node has whitelist, make sure the user has a slice on the whitelist
59             for node in nodes[:]:
60                 if 'slice_ids_whitelist' in node and \
61                    node['slice_ids_whitelist'] and \
62                    not slice_ids.intersection(node['slice_ids_whitelist']):
63                     nodes.remove(node)
64             for node in nodes:
65                 for field in ['boot_nonce', 'key', 'session', 'root_person_ids']:
66                     if field in node:
67                         del node[field]
68
69         # remove added fields if not specified
70         if added_fields:
71             for node in nodes:
72                 for field in added_fields:
73                     del node[field]
74
75         return nodes