#!/usr/local/qcloud/monitor/python26/bin/python # -*- coding: utf-8 -*- __author__ = 'samhuang' # ********************************************************************* # Description : cloud monitor agent tool # # Input parameters : # # Output Parameters : # # created by : samhuang, 2014-Feb-13 # return state value: null # note : # # modified by : hetiulin, 2014-Oct-27 # ********************************************************************* import sys import urllib2, time, json, os realPath = os.path.dirname(os.path.realpath(__file__)) + '/../comm/' sys.path.append(realPath) import cutils import constant sys.path.append(os.getcwd()+"/../plugin/collector/utils/") from collect_vm_msg import CollectVmMesg class AlarmSender: def __init__(self): self.__config = cutils.generate_config(constant.PLUGIN_CONFIG_PATH, self.__class__.__name__) self.metadata = CollectVmMesg() def sendData(self, data, policy_id): try: data['localip'] = cutils.local_ip() data['clientKey'] = self.metadata.get_client_key() data['localtime'] = int(time.time()) with open('/etc/uuid', 'r') as f: uuid = f.read().split('=')[1].replace('"', '').replace('\'', '').strip() data['uuid'] = uuid if policy_id is not None: data['policyId'] = policy_id url = cutils.get_url('AlarmSender','new_alarm_url','alarm_url') timeout = float(self.__config['alarm_timeout']) / 1000 http_ret = urllib2.urlopen(url, json.dumps(data), timeout) response = http_ret.read() try: json_resp = json.loads(response) retcode = int(json_resp["returnCode"]) if retcode != 0: error_msg = json_resp["msg"] (retcode, retinfo) = (constant.ErrorCode.HTTP_RESPONSE_ERROR, error_msg) else: (retcode, retinfo) = (constant.ErrorCode.SUCC, "OK") except ValueError, e: (retcode, retinfo) = (constant.ErrorCode.HTTP_RESPONSE_ERROR, "server return an invalid data") except urllib2.URLError, e: (retcode, retinfo) = (constant.ErrorCode.HTTP_SEND_ERROR, "send to server failed") return (retcode, retinfo) def help(): print 'usage: %s args' % sys.argv[0] print '\tsubcommand list as:' print '\talarm alarmString policyId' +\ '\n\t\texample:%s alarm "hello world" cm-ah7hc3md (policyId can be acquired from the cloud monitor console)' % sys.argv[0] exit(0) # const variable definitions MAX_ALARM_LEN = 1024 # ------ program start here ------------ if len(sys.argv) < 3 or len(sys.argv) > 4: help() subCmd = sys.argv[1] if cmp(subCmd, 'alarm') == 0: if len(sys.argv[2]) > MAX_ALARM_LEN: print "alarm string's length is over the max length %d, please shorten it" % MAX_ALARM_LEN exit(1) alarm_str = {'alarmString': sys.argv[2]} policy_id = sys.argv[3] if len(sys.argv) == 4 else None alarmObj = AlarmSender() ret_code, ret_msg = alarmObj.sendData(alarm_str, policy_id) if ret_code == 0: print "send alarm string OK!" else: print "fail to send alarm string as " + ret_msg + ", please try again!" exit(ret_code) else: help()