force import of AuthorizeHelpers
[plcapi.git] / PLC / Methods / AddInterfaceTag.py
1 #
2 # Thierry Parmentelat - INRIA
3 #
4 from PLC.Faults import *
5 from PLC.Method import Method
6 from PLC.Parameter import Parameter, Mixed
7 from PLC.Auth import Auth
8
9 from PLC.Sites import Sites
10 from PLC.Nodes import Nodes
11 from PLC.Interfaces import Interface, Interfaces
12 from PLC.TagTypes import TagType, TagTypes
13 from PLC.InterfaceTags import InterfaceTag, InterfaceTags
14
15 # need to import so the core classes get decorated with caller_may_write_tag
16 from PLC.AuthorizeHelpers import AuthorizeHelpers
17
18 class AddInterfaceTag(Method):
19     """
20     Sets the specified setting for the specified interface
21     to the specified value.
22
23     Admins have full access.  Non-admins need to 
24     (1) have at least one of the roles attached to the tagtype, 
25     and (2) belong in the same site as the tagged subject.
26
27     Returns the new interface_tag_id (> 0) if successful, faults
28     otherwise.
29     """
30
31     roles = ['admin', 'pi', 'tech', 'user']
32
33     accepts = [
34         Auth(),
35         # no other way to refer to a interface
36         InterfaceTag.fields['interface_id'],
37         Mixed(TagType.fields['tag_type_id'],
38               TagType.fields['tagname']),
39         InterfaceTag.fields['value'],
40         ]
41
42     returns = Parameter(int, 'New interface_tag_id (> 0) if successful')
43
44     def call(self, auth, interface_id, tag_type_id_or_name, value):
45         interfaces = Interfaces(self.api, [interface_id])
46         if not interfaces:
47             raise PLCInvalidArgument, "No such interface %r"%interface_id
48         interface = interfaces[0]
49
50         tag_types = TagTypes(self.api, [tag_type_id_or_name])
51         if not tag_types:
52             raise PLCInvalidArgument, "No such tag type %r"%tag_type_id_or_name
53         tag_type = tag_types[0]
54
55         # checks for existence - does not allow several different settings
56         conflicts = InterfaceTags(self.api,
57                                         {'interface_id':interface['interface_id'],
58                                          'tag_type_id':tag_type['tag_type_id']})
59
60         if len(conflicts) :
61             raise PLCInvalidArgument, "Interface %d already has setting %d"%(interface['interface_id'],
62                                                                                tag_type['tag_type_id'])
63
64         # check authorizations
65         interface.caller_may_write_tag(self.api,self.caller,tag_type)
66
67         interface_tag = InterfaceTag(self.api)
68         interface_tag['interface_id'] = interface['interface_id']
69         interface_tag['tag_type_id'] = tag_type['tag_type_id']
70         interface_tag['value'] = value
71
72         interface_tag.sync()
73         self.object_ids = [interface_tag['interface_tag_id']]
74
75         return interface_tag['interface_tag_id']