c95c57d0dc62c8b8d0746c001e50853f7bd639b1
[plcapi.git] / PLC / Methods / ReportRunlevel.py
1 # $Id$
2 from PLC.Faults import *
3 from PLC.Method import Method
4 from PLC.Parameter import Parameter, Mixed
5 from PLC.Auth import Auth, BootAuth, SessionAuth
6 from PLC.Nodes import Node, Nodes
7
8 can_update = ['run_level']
9
10 class ReportRunlevel(Method):
11     """
12         report runlevel
13     """
14     roles = ['node', 'admin']
15
16     accepts = [
17         Mixed(BootAuth(), SessionAuth(), Auth()),
18         {'run_level': Node.fields['run_level'],
19          },
20         Mixed(Node.fields['node_id'],
21               Node.fields['hostname'])
22         ]
23
24     returns = Parameter(int, '1 if successful')
25
26     def call(self, auth, report_fields, node_id_or_hostname=None):
27
28         if not isinstance(self.caller, Node):
29             # check admin
30             if 'admin' not in self.caller['roles']:
31                 raise PLCPermissionDenied, "Not allowed to update node run_level"
32
33             nodes = Nodes(self.api, [node_id_or_hostname])
34             if not nodes:
35                 raise PLCInvalidArgument, "No such node"
36         else:
37             nodes  = [self.caller]
38
39         node = nodes[0]
40         # avoid logging this even too often
41         # avoid logging occurrences where run_level does not change
42         former_level=None
43         if 'run_level' in node: former_level=node['run_level']
44
45         node.update_last_contact()
46         for field in can_update:
47             if field in report_fields:
48                 node.update({field : report_fields[field]})
49
50         node.sync(commit=True)
51         
52         # skip logging in this case
53         if former_level and 'run_level' in node and node['run_level'] == former_level:
54             pass
55         else:
56             # handle the 'run_level' key
57             message="run level " + node['hostname'] + ":"
58             if 'run_level' in report_fields:
59                 message += str(former_level) + "->" + report_fields['run_level']
60             message += ", ".join(  [ k + "->" + v for (k,v) in report_fields.items() if k not in ['run_level'] ] )
61
62         return 1