bca8ab63ca326bad3f6f188ff4ac6a81609c1f53
[packages/precise/mcollective.git] / ext / action_helpers / python / romke / mcollectiveah.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*- vim: set ts=4 et sw=4 fdm=indent :
3 import os, sys
4
5 try:
6     import simplejson
7 except ImportError:
8     sys.stderr.write('Unable to load simplejson python module.')
9     sys.exit(1)
10
11 class MCollectiveActionNoEnv(Exception):
12     pass
13 class MCollectiveActionFileError(Exception):
14     pass
15
16 class MCollectiveAction(object):
17     def __init__(self, *args, **kwargs):
18         try:
19             self.infile = os.environ['MCOLLECTIVE_REQUEST_FILE']
20         except KeyError:
21             raise MCollectiveActionNoEnv("No MCOLLECTIVE_REQUEST_FILE environment variable")
22         try:
23             self.outfile = os.environ['MCOLLECTIVE_REPLY_FILE']
24         except KeyError:
25             raise MCollectiveActionNoEnv("No MCOLLECTIVE_REPLY_FILE environment variable")
26
27         self.request = {}
28         self.reply = {}
29
30         self.load()
31
32     def load(self):
33         if not self.infile:
34             return False
35         try:
36             infile = open(self.infile, 'r')
37             self.request = simplejson.load(infile)
38             infile.close()
39         except IOError, e:
40             raise MCollectiveActionFileError("Could not read request file `%s`: %s" % (self.infile, e))
41         except simplejson.JSONDecodeError, e:
42             infile.close()
43             raise MCollectiveActionFileError("Could not parse JSON data in file `%s`: %s", (self.infile, e))
44
45     def send(self):
46         if not getattr(self, 'outfile', None): # if exception was raised during or before setting self.outfile
47             return False
48         try:
49             outfile = open(self.outfile, 'w')
50             simplejson.dump(self.reply, outfile)
51             outfile.close()
52         except IOError, e:
53             raise MCollectiveActionFileError("Could not write reply file `%s`: %s" % (self.outfile, e))
54
55     def error(self, msg):
56         """Prints line to STDERR that will be logged at error level in the mcollectived log file"""
57         sys.stderr.write("%s\n" % msg)
58
59     def fail(self, msg):
60         """Logs error message and exitst with RPCAborted"""
61         self.error(msg)
62         sys.exit(1)
63
64     def info(self, msg):
65         """Prints line to STDOUT that will be logged at info level in the mcollectived log file"""
66         sys.stdout.write("%s\n" % msg)
67
68     def __del__(self):
69         self.send()