Add 'php/phpxmlrpc/' from commit 'cd5dbb4a511e7a616a61187a5de1a611a9748cbd'
[plcapi.git] / PLC / Methods / AddNodeTag.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 Node, Nodes
11 from PLC.TagTypes import TagType, TagTypes
12 from PLC.NodeTags import NodeTag, NodeTags
13
14 # need to import so the core classes get decorated with caller_may_write_tag
15 from PLC.AuthorizeHelpers import AuthorizeHelpers
16
17 class AddNodeTag(Method):
18     """
19     Sets the specified tag for the specified node
20     to the specified value.
21
22     Admins have full access.  Non-admins need to 
23     (1) have at least one of the roles attached to the tagtype, 
24     and (2) belong in the same site as the tagged subject.
25
26     Returns the new node_tag_id (> 0) if successful, faults
27     otherwise.
28     """
29
30     roles = ['admin', 'pi', 'tech', 'user']
31
32     accepts = [
33         Auth(),
34         # no other way to refer to a node
35         Mixed(Node.fields['node_id'],
36               Node.fields['hostname']),
37         Mixed(TagType.fields['tag_type_id'],
38               TagType.fields['tagname']),
39         NodeTag.fields['value'],
40         ]
41
42     returns = Parameter(int, 'New node_tag_id (> 0) if successful')
43
44     def call(self, auth, node_id, tag_type_id_or_name, value):
45         nodes = Nodes(self.api, [node_id])
46         if not nodes:
47             raise PLCInvalidArgument, "No such node %r"%node_id
48         node = nodes[0]
49
50         tag_types = TagTypes(self.api, [tag_type_id_or_name])
51         if not tag_types:
52             raise PLCInvalidArgument, "No such node tag type %r"%tag_type_id_or_name
53         tag_type = tag_types[0]
54
55         # checks for existence - does not allow several different tags
56         conflicts = NodeTags(self.api,
57                                         {'node_id':node['node_id'],
58                                          'tag_type_id':tag_type['tag_type_id']})
59
60         if len(conflicts) :
61             raise PLCInvalidArgument, "Node %d already has tag %d"%(node['node_id'],
62                                                                     tag_type['tag_type_id'])
63
64         # check authorizations
65         node.caller_may_write_tag(self.api,self.caller,tag_type)
66
67         node_tag = NodeTag(self.api)
68         node_tag['node_id'] = node['node_id']
69         node_tag['tag_type_id'] = tag_type['tag_type_id']
70         node_tag['value'] = value
71
72         node_tag.sync()
73         self.object_ids = [node_tag['node_tag_id']]
74
75         return node_tag['node_tag_id']