def run_task(self, task):
		print 'RUN TASK 1 ##############'
		print task
		for server in task.value:
			for _type in self.sources:
				key = '%s_%s' % (_type, str(server))
				try:
					cache_data = DW.cache_key_get(key)
					if type(eval(str(cache_data))) is dict:
						try:
							task.value[server][_type] = GenericDataObject(eval(str(cache_data)))
							if task.value[server][_type].warnings[server] != None:
								print 'RED FLAG: %s %s' % (server, _type)
								print task.value[server][_type].warnings
							else:
								task.value[server][_type].health_indicator = CommonMath.adaptive_filtration(
									task.value[server][_type].normalized_indicator,
									task.value[server][_type].multiplier,
									task.value[server][_type].threshold_red,
									task.value[server][_type].scale
									)
						except Exception, e:
							print 'ERROR 1: %s' % e
				except Exception, e:
					CommonLogger.log(e, 'create_health_metrics', 'run_task-<%s-%s>' % (server, _type))
					print 'ERROR 2: %s' % e
					return jsonify({'response': {'error': str(e)}})
示例#2
0
 def run_task(self, task):
     print 'RUN TASK 1 ##############'
     print task
     for server in task.value:
         for _type in self.sources:
             key = '%s_%s' % (_type, str(server))
             try:
                 cache_data = DW.cache_key_get(key)
                 if type(eval(str(cache_data))) is dict:
                     try:
                         task.value[server][_type] = GenericDataObject(
                             eval(str(cache_data)))
                         if task.value[server][_type].warnings[
                                 server] != None:
                             print 'RED FLAG: %s %s' % (server, _type)
                             print task.value[server][_type].warnings
                         else:
                             task.value[server][
                                 _type].health_indicator = CommonMath.adaptive_filtration(
                                     task.value[server]
                                     [_type].normalized_indicator,
                                     task.value[server][_type].multiplier,
                                     task.value[server]
                                     [_type].threshold_red,
                                     task.value[server][_type].scale)
                     except Exception, e:
                         print 'ERROR 1: %s' % e
             except Exception, e:
                 CommonLogger.log(e, 'create_health_metrics',
                                  'run_task-<%s-%s>' % (server, _type))
                 print 'ERROR 2: %s' % e
                 return jsonify({'response': {'error': str(e)}})
	def api_get_production_servers():
		if request.method == 'GET':
			return jsonify(ResourceGetProductionServers()._show_help())
		try:
			data = CommonResource.handle_request(request, ResourceGetProductionServers.required_post)
		except Exception, e:
			CommonLogger.log(e, 'get_production_servers', 'api_get_production_servers')
			return jsonify({'response': {'error': str(e)}})
示例#4
0
	def api_get_all_roles():
		if request.method == 'GET':
			return jsonify(ResourceGetAllRoles()._show_help())
		try:
			data = CommonResource.handle_request(request, ResourceGetAllRoles.required_post)
		except Exception, e:
			CommonLogger.log(e, 'get_all_roles', 'api_get_all_roles')
			return jsonify({'response': {'error': str(e)}})
示例#5
0
class ResourceDashboard(AxolResource):
	"""docstring for ResourceDashboard
	Must implement:

	"""

	def __init__(self):
		super(ResourceDashboard, self).__init__()
		pass

	@staticmethod
	@app.route('/api/readonly/dashboard/', methods=['GET'])
	def request_dashboard_api():
		sources = [
			'cpu',
			'memory',
			'disk',
			'mysql',
			'mean',
			'deviation_pos',
			'deviation_neg'
			]
		t = time.time()
		response = DW.cache_key_get('roledefs')
		warnings = DW.cache_key_get('ro_warnings')
		server_dict = ResourceDashboard().create_server_list(
			literal_eval(response),
			'production_servers'
			)
		response_dict = {
			'response': {
				'value': {}
				},
			'warnings': {}
			}
		response_dict['warnings'] = literal_eval(warnings)
		error_dict = {}
		for server in server_dict:
			response_dict['response']['value'][server] = {}
			for source in sources:
				key = 'ro_%s_%s' % (source, server)
				try:
					response = DW.cache_key_get(key)
					response_dict['response']['value'][server][source] = literal_eval(response)
				except Exception, e:
					error_dict[key] = str(e)
		if error_dict != {}:
			CommonLogger.log(error_dict, 'dashboard', 'request_dashboard_api')
		t2 = time.time()
		t3 = t2 - t
		response_dict['response']['time'] = round(t3, 4)
		print 'complete'
		try:
			return jsonify(response_dict)
		except Exception, e:
			CommonLogger.log(str(e), 'dashboard', 'request_dashboard_api')
			print e
示例#6
0
	def api_remove_alert_server():
		role = 'production_servers'
		if request.method == 'GET':
			return jsonify(ResourceRemoveAlertServer()._show_help())
		try:
			data = CommonResource.handle_request(request, ResourceRemoveAlertServer.required_post)
		except Exception, e:
			CommonLogger.log(e, 'remove_alert_server', 'api_remove_alert_server')
			return jsonify({'response': {'error': str(e)}})
示例#7
0
	def async_job(self, data):
		async_job_time = time.time()
		try:
			new_data_object = GenericDataObject(data.return_attribute_dict())
			new_data_object.data = data.return_attribute_dict()
			data = ''
			new_data_object.source = self.source
			new_data_object.resource = self
			AxolTask = TaskEngine().run_task(new_data_object)
		except Exception, e:
			CommonLogger.log(e, 'axol_resource', 'async_job')
示例#8
0
 def async_job(self, data):
     async_job_time = time.time()
     try:
         new_data_object = GenericDataObject(data.return_attribute_dict())
         new_data_object.data = data.return_attribute_dict()
         data = ""
         new_data_object.source = self.source
         new_data_object.resource = self
         AxolTask = TaskEngine().run_task(new_data_object)
     except Exception, e:
         CommonLogger.log(e, "axol_resource", "async_job")
示例#9
0
 def threshold_validation(self, response_object):
     data = {
         "error": "Current health: %s, below threshold: %s on %s"
         % (response_object.health_indicator, response_object.threshold_red, response_object.name)
     }
     if response_object.health_indicator < 0:
         try:
             self.send_notice(name="threshold_validation", data=data, group="default", alert_type=["email"])
         except Exception, e:
             status = "incomplete"
             CommonLogger.log(e, "threshold_validation", "threshold_validation")
         response_object.warnings[response_object.name] = data["error"]
示例#10
0
 def run_task(self, AxolTask):
     AxolTask.name = 'event_notice'
     AxolTask.api = api
     AxolTask.api['api_name'] = 'create_event_notice'
     if AxolTask.data['alert_type'] != []:
         try:
             ResourceCreateEventNotice().send_notice(
                 name=AxolTask.name,
                 data=AxolTask.data,
                 group=AxolTask.data['group'],
                 alert_type=AxolTask.data['alert_type'])
         except Exception, e:
             status = 'incomplete'
             CommonLogger.log(e, 'create_event_notice',
                              'api_create_event_notice')
	def run_task(self, AxolTask):
		AxolTask.name = 'event_notice'
		AxolTask.api = api
		AxolTask.api['api_name'] = 'create_event_notice'
		if AxolTask.data['alert_type'] != []:
			try:
				ResourceCreateEventNotice().send_notice(
					name=AxolTask.name,
					data=AxolTask.data,
					group=AxolTask.data['group'],
					alert_type=AxolTask.data['alert_type']
					)
			except Exception, e:
				status = 'incomplete'
				CommonLogger.log(e, 'create_event_notice', 'api_create_event_notice')
示例#12
0
class TaskEngine(object):
    """docstring for TaskEngine"""
    def __init__(self):
        super(TaskEngine, self).__init__()
        self.AxolTask = AxolTask()
        self.error_types = [
            'None', 'null', 'Timed out', 'Low level', 'Name look'
        ]

    def set_engine(self, engine):
        self.engine = engine
        self.engine.conf.update(CELERY_TASK_RESULT_EXPIRES=30, )

# Per task methods
#-----------------------------------------------------------------------#

    def run_task(self, new_data_object):
        try:
            roledefs = literal_eval(DW.cache_key_get('roledefs'))
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='task_engine',
                                      method='cache_key_get')
            return report
        print '### build task'
        try:
            self._build_task(roledefs=roledefs, data=new_data_object)
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='task_engine',
                                      method='build_task')
            return report
示例#13
0
 def run_task(self, AxolTask):
     AxolTask.name = 'log_entry'
     AxolTask.api = api
     AxolTask.api['api_name'] = 'create_log_entry'
     self.store = AxolTask.data['log']
     if AxolTask.data['alert_type'] != []:
         try:
             ResourceCreateLogEntry().send_notice(
                 name=AxolTask.name,
                 data=AxolTask.data,
                 group=AxolTask.data['group'],
                 alert_type=AxolTask.data['alert_type'])
         except Exception, e:
             print 'ERROR: RCL notice: %s' % e
             status = 'incomplete'
             CommonLogger.log(e, 'create_log_entry', 'api_create_log_entry')
 def api_get_recent_transactions():
     if request.method == "GET":
         return jsonify(ResourceGetRecentTransactions()._show_help())
     try:
         data = CommonResource.handle_request(request=request, params=ResourceGetRecentTransactions.required_post)
     except Exception, e:
         report = CommonLogger.log(error=e, source="get_recent_transactions", method="api_get_recent_transactions-1")
         return jsonify(report)
示例#15
0
 def run_task(self, new_data_object):
     try:
         roledefs = literal_eval(DW.cache_key_get('roledefs'))
     except Exception, e:
         report = CommonLogger.log(error=e,
                                   source='task_engine',
                                   method='cache_key_get')
         return report
	def run_task(self, AxolTask):
		AxolTask.name = 'log_entry'
		AxolTask.api = api
		AxolTask.api['api_name'] = 'create_log_entry'
		self.store = AxolTask.data['log']
		if AxolTask.data['alert_type'] != []:
			try:
				ResourceCreateLogEntry().send_notice(
					name=AxolTask.name,
					data=AxolTask.data,
					group=AxolTask.data['group'],
					alert_type=AxolTask.data['alert_type']
					)
			except Exception, e:
				print 'ERROR: RCL notice: %s' % e
				status = 'incomplete'
				CommonLogger.log(e, 'create_log_entry', 'api_create_log_entry')
示例#17
0
	def threshold_validation(self, response_object):
		data = {'error': 'Current health: %s, below threshold: %s on %s' % (
			response_object.health_indicator,
			response_object.threshold_red,
			response_object.name
			)}
		if response_object.health_indicator < 0:
			try:
				self.send_notice(
					name='threshold_validation',
					data=data,
					group='default',
					alert_type=['email']
					)
			except Exception, e:
				status = 'incomplete'
				CommonLogger.log(e, 'threshold_validation', 'threshold_validation')
			response_object.warnings[response_object.name] = data['error']
class ResourceGetRecentTransactions(AxolResource):
    """docstring for ResourceGetRecentTransactions
	Must implement:
		_show_help()
		self.source = {keyword}
		self.local = Bool
		self.store = Bool
		self.profiler = Bool
		api_<name of your api>()
		calculate_new_fields()
		write_to_database()
	Optional:
		if self.store = True, write_to_database() function must be implemented
	"""
    required_post = {'role': (True, u's'), 'profile': (False, u's')}

    def __init__(self):
        super(ResourceGetRecentTransactions, self).__init__()
        self.source = 'get_recent_transactions'
        self.local = False
        self.store = True
        self.profiler = True

    def _show_help(self):
        return {
            'help': {
                'usage': '/api/get_recent_transactions',
                'method': 'POST',
                'required_data': {
                    'role': '<some role>'
                },
                'version': api
            }
        }

    @staticmethod
    @app.route('/api/get_recent_transactions', methods=['GET', 'POST'])
    def api_get_recent_transactions():
        if request.method == 'GET':
            return jsonify(ResourceGetRecentTransactions()._show_help())
        try:
            data = CommonResource.handle_request(
                request=request,
                params=ResourceGetRecentTransactions.required_post)
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='get_recent_transactions',
                                      method='api_get_recent_transactions-1')
            return jsonify(report)
        try:
            response = ResourceGetRecentTransactions().create_async_job(
                data=data)
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='get_recent_transactions',
                                      method='api_get_recent_transactions-2')
            return jsonify(report)
示例#19
0
	def notification_threshold(self, AxolTask):
		def process_notification(name, AxolTask, key):
			notification_status = DW.cache_key_get(key)
			print '<Notification Status>: %s' % notification_status
			if notification_status == None:
				default = {
					'warn_threshold': 0,
					'silence_threshold': 0
					}
				DW.cache_key_set(key, default)
				notification_status = DW.cache_key_get(key)
			ns = literal_eval(notification_status)
			ns['warn_threshold'] += 1
			if (7 >= ns['warn_threshold'] > 4 and ns['silence_threshold'] == 0):
				self.send_notice(
					name=AxolTask.name,
					data=AxolTask.value,
					group='default',
					alert_type=['email', 'text']
					)
				DW.cache_key_set(key, ns)
				return 1
			elif (ns['warn_threshold'] > 4 and ns['silence_threshold'] <= 12):
				ns['silence_threshold'] += 1
				DW.cache_key_set(key, ns)
				return 1
			elif ns['silence_threshold'] > 12:
				ns['warn_threshold'] = 5
				ns['silence_threshold'] = 0
				DW.cache_key_set(key, ns)
				return 1
			DW.cache_key_set(key, ns)
			return 1

		key = 'notification_threshold'
		if len(AxolTask.value) > 0:
			for server in AxolTask.value:
				if server != 'status':
					if AxolTask.value[server] != []:
						print '<Task Warnings>: %s' % AxolTask.value[server]
						try:
							process_notification(server, AxolTask, key)
						except Exception, e:
							CommonLogger.log(e, 'axol_resource', 'process_notification')
示例#20
0
	def run_task(self, new_data_object):
		try:
			roledefs = literal_eval(DW.cache_key_get('roledefs'))
		except Exception, e:
			report = CommonLogger.log(
				error=e,
				source='task_engine',
				method='cache_key_get'
				)
			return report
示例#21
0
 def api_create_log_entry():
     if request.method == 'GET':
         return jsonify(ResourceCreateLogEntry()._show_help())
     try:
         data = CommonResource.handle_request(
             request=request, params=ResourceCreateLogEntry.required_post)
     except Exception, e:
         report = CommonLogger.log(error=e,
                                   source='create_log_entry',
                                   method='api_create_log_entry-1')
         return jsonify(report)
 def api_get_disk_usage():
     if request.method == 'GET':
         return jsonify(ResourceGetDiskUsage()._show_help())
     try:
         data = CommonResource.handle_request(
             request=request, params=ResourceGetDiskUsage.required_post)
     except Exception, e:
         report = CommonLogger.log(error=e,
                                   source='get_disk_usage',
                                   method='api_get_disk_usage')
         return jsonify(report)
示例#23
0
	def request_cpu_api():
		# Return help for 'GET' requests
		if request.method == 'GET':
			return jsonify(ResourceGetProductionServers()._show_help())

		# data is an object with all your first level POST fields as attributes
		data = CommonResource.handle_request(request, ResourceGetProductionServers.required_post)

		try:

# Add your request handling code here
#-----------------------------------------------------------------------#

			# use this if you have an agent plugin and want to execute async tasks
			response = ResourceTemplate().create_async_job(data)

# Built-in error handling
#-----------------------------------------------------------------------#
		except Exception, e:
			CommonLogger.log(e, self.source, 'request_cpu_api')
			return jsonify({'response': {'error': str(e)}})
示例#24
0
class ResourceRemoveAlertServer(AxolResource):
	"""docstring for ResourceRemoveAlertServer
	Must implement:
		_show_help
		self.methods = {<method_type>: function}
		self.source = {keyword}
		request_{keyword}_api
		calculate_new_fields
	"""
	required_post = {
		'server_name': (True, u's'),
		'profile': (False, u's')
		}

	def __init__(self):
		super(ResourceRemoveAlertServer, self).__init__()
		self.source = 'remove_alert_servers'
		self.local = True

	def _show_help(self):
		return {
			'Help': {
				'api': '/api/remove_alert_servers',
				'method': 'POST',
				'required data':  {
					'server_name': '<name of the server to remove>'
					},
				'version': api
				}
			}

	@staticmethod
	@app.route('/api/remove_alert_server', methods=['POST', 'GET'])
	def api_remove_alert_server():
		role = 'production_servers'
		if request.method == 'GET':
			return jsonify(ResourceRemoveAlertServer()._show_help())
		try:
			data = CommonResource.handle_request(request, ResourceRemoveAlertServer.required_post)
		except Exception, e:
			CommonLogger.log(e, 'remove_alert_server', 'api_remove_alert_server')
			return jsonify({'response': {'error': str(e)}})
		try:
			roledefs = literal_eval(DW.cache_key_get('roledefs'))
			server_dict = ResourceRemoveAlertServer.create_server_list(roledefs, role)
			if server_dict[data.server_name] in roledefs[role]:
				roledefs[role].remove(server_dict[data.server_name])
				DW.cache_key_set('roledefs', roledefs)
			if data.server_name in server_dict.keys():
				del server_dict[data.server_name]
		except Exception, e:
			CommonLogger.log(e, 'remove_alert_server', 'api_remove_alert_server')
			return jsonify({'response': {'error': str(e)}})
 def api_get_recent_transactions():
     if request.method == 'GET':
         return jsonify(ResourceGetRecentTransactions()._show_help())
     try:
         data = CommonResource.handle_request(
             request=request,
             params=ResourceGetRecentTransactions.required_post)
     except Exception, e:
         report = CommonLogger.log(error=e,
                                   source='get_recent_transactions',
                                   method='api_get_recent_transactions-1')
         return jsonify(report)
	def api_get_disk_usage():
		if request.method == 'GET':
			return jsonify(ResourceGetDiskUsage()._show_help())
		try:
			data = CommonResource.handle_request(
				request=request,
				params=ResourceGetDiskUsage.required_post
				)
		except Exception, e:
			report = CommonLogger.log(
				error=e,
				source='get_disk_usage',
				method='api_get_disk_usage'
				)
			return jsonify(report)
示例#27
0
	def api_send_warnings_alerts():
		if request.method == 'GET':
			return jsonify(ResourceSendWarningsAlerts()._show_help())
		try:
			data = CommonResource.handle_request(
				request=request,
				params=ResourceSendWarningsAlerts.required_post
				)
		except Exception, e:
			report = CommonLogger.log(
				error=e,
				source='create_event_notice',
				method='api_create_event_notice-1'
				)
			return jsonify(report)
	def api_create_log_entry():
		if request.method == 'GET':
			return jsonify(ResourceCreateLogEntry()._show_help())
		try:
			data = CommonResource.handle_request(
				request=request,
				params=ResourceCreateLogEntry.required_post
				)
		except Exception, e:
			report = CommonLogger.log(
				error=e,
				source='create_log_entry',
				method='api_create_log_entry-1'
				)
			return jsonify(report)
示例#29
0
    def notification_threshold(self, AxolTask):
        def process_notification(name, AxolTask, key):
            notification_status = DW.cache_key_get(key)
            print "<Notification Status>: %s" % notification_status
            if notification_status == None:
                default = {"warn_threshold": 0, "silence_threshold": 0}
                DW.cache_key_set(key, default)
                notification_status = DW.cache_key_get(key)
            ns = literal_eval(notification_status)
            ns["warn_threshold"] += 1
            if 7 >= ns["warn_threshold"] > 4 and ns["silence_threshold"] == 0:
                self.send_notice(name=AxolTask.name, data=AxolTask.value, group="default", alert_type=["email", "text"])
                DW.cache_key_set(key, ns)
                return 1
            elif ns["warn_threshold"] > 4 and ns["silence_threshold"] <= 12:
                ns["silence_threshold"] += 1
                DW.cache_key_set(key, ns)
                return 1
            elif ns["silence_threshold"] > 12:
                ns["warn_threshold"] = 5
                ns["silence_threshold"] = 0
                DW.cache_key_set(key, ns)
                return 1
            DW.cache_key_set(key, ns)
            return 1

        key = "notification_threshold"
        if len(AxolTask.value) > 0:
            for server in AxolTask.value:
                if server != "status":
                    if AxolTask.value[server] != []:
                        print "<Task Warnings>: %s" % AxolTask.value[server]
                        try:
                            process_notification(server, AxolTask, key)
                        except Exception, e:
                            CommonLogger.log(e, "axol_resource", "process_notification")
class ResourceGetProductionServers(AxolResource):
    """docstring for ResourceGetProductionServers
	Must implement:
		_show_help
		self.methods = {<method_type>: function}
		self.source = {keyword}
		request_{keyword}_api
		calculate_new_fields
	"""
    required_post = {'network': (True, u's'), 'profile': (False, u's')}

    def __init__(self):
        super(ResourceGetProductionServers, self).__init__()
        self.source = 'get_production_servers'
        self.local = True

    def _show_help(self):
        return {
            'Help': {
                'api': '/api/get_production_servers',
                'method': 'POST',
                'required data': {
                    'network': '<internal, external>'
                },
                'version': api
            }
        }

    @staticmethod
    @app.route('/api/get_production_servers', methods=['POST', 'GET'])
    def api_get_production_servers():
        if request.method == 'GET':
            return jsonify(ResourceGetProductionServers()._show_help())
        try:
            data = CommonResource.handle_request(
                request, ResourceGetProductionServers.required_post)
        except Exception, e:
            CommonLogger.log(e, 'get_production_servers',
                             'api_get_production_servers')
            return jsonify({'response': {'error': str(e)}})
        try:
            roledefs = generate_base_roles(data.network)
            server_dict = ResourceGetProductionServers.create_server_list(
                roledefs, 'production_servers')
        except Exception, e:
            CommonLogger.log(e, 'get_production_servers',
                             'api_get_production_servers')
            return jsonify({'response': {'error': str(e)}})
示例#31
0
class ResourceGetMysqlUsage(AxolResource):
    """docstring for ResourceGetMysqlUsage
	Must implement:
		_show_help
		self.methods = {<method_type>: function}
		self.source = {keyword}
		request_{keyword}_api
		calculate_new_fields
	"""
    required_post = {'role': (True, u's'), 'profile': (False, u's')}

    def __init__(self):
        super(ResourceGetMysqlUsage, self).__init__()
        self.source = 'mysql'
        self.local = False

    def _show_help(self):
        return {
            'help': {
                'usage': '/api/get_mysql_usage',
                'method': 'POST',
                'required_data': {
                    'role': '<some role>',
                    'alert_type': ['email', 'text']
                },
                'version': api
            }
        }

    @staticmethod
    @app.route('/api/get_mysql_usage', methods=['GET', 'POST'])
    def api_get_mysql_usage():
        if request.method == 'GET':
            return jsonify(ResourceGetMysqlUsage()._show_help())
        try:
            data = CommonResource.handle_request(
                request, ResourceGetMysqlUsage.required_post)
        except Exception, e:
            CommonLogger.log(e, 'get_mysql_usage', 'api_get_mysql_usage')
            return jsonify({'response': {'error': str(e)}})
        try:
            response = ResourceGetMysqlUsage().create_async_job(data)
        except Exception, e:
            CommonLogger.log(e, 'get_mysql_usage', 'api_get_mysql_usage')
            return jsonify({'response': {'error': str(e)}})
示例#32
0
class ResourceCreateEventNotice(AxolResource):
    """docstring for ResourceCreateEventNotice
	Must implement:
		_show_help()
		self.source = {keyword}
		self.local = Bool
		self.store = Bool
		self.profiler = Bool
		api_<name of your api>()
		calculate_new_fields()
		write_to_database()
	Optional:
		if self.store = True, write_to_database() function must be implemented
	"""
    required_post = {
        'alert_type': (True, []),
        'source': (True, U's'),
        'group': (True, U's'),
        'data': (True, {}),
        'profile': (False, U's')
    }

    def __init__(self):
        super(ResourceCreateEventNotice, self).__init__()
        self.source = 'events'
        self.local = True
        self.store = True
        self.profiler = True

    def _show_help(self):
        return {
            'help': {
                'usage': '/api/create_event_notice',
                'method': 'POST',
                'required_data': {
                    'alert_type': '<list of prefered types>',
                    'source': '<type of event>',
                    'group': '<group name>',
                    'data': '<some json>',
                },
                'version': api
            }
        }

    @staticmethod
    @app.route('/api/create_event_notice', methods=['GET', 'POST'])
    def api_create_event_notice():
        if request.method == 'GET':
            return jsonify(ResourceCreateEventNotice()._show_help())
        try:
            data = CommonResource.handle_request(
                request=request,
                params=ResourceCreateEventNotice.required_post)
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='create_event_notice',
                                      method='api_create_event_notice-1')
            return jsonify(report)
        try:
            response = ResourceCreateEventNotice().create_async_job(data=data)
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='create_event_notice',
                                      method='api_create_event_notice-2')
            return jsonify(report)
				)
		except Exception, e:
			report = CommonLogger.log(
				error=e,
				source='create_health_metrics',
				method='api_create_health_metrics-2'
				)
			return jsonify(report)
		try:
			ResourceCreateHealthMetrics().populate_cache(
				response=response['response']
				)
		except Exception, e:
			report = CommonLogger.log(
				error=e,
				source='create_health_metrics',
				method='api_create_health_metrics-3'
				)
			return jsonify(report)
		return jsonify(response)

	def populate_cache(self, response):
		server_dict = {}
		print response
		print '##################'
		response['api'] = api
		response['api']['api_name'] = 'health'
		for item in response['value']:
			print '1111'
			print response['value'][item]
			response['value'][item] = response['value'][item]
示例#34
0
                                      method='api_create_health_metrics-1')
            return jsonify(report)
        try:
            response = ResourceCreateHealthMetrics().create_async_job(
                data=data)
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='create_health_metrics',
                                      method='api_create_health_metrics-2')
            return jsonify(report)
        try:
            ResourceCreateHealthMetrics().populate_cache(
                response=response['response'])
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='create_health_metrics',
                                      method='api_create_health_metrics-3')
            return jsonify(report)
        return jsonify(response)

    def populate_cache(self, response):
        server_dict = {}
        print response
        print '##################'
        response['api'] = api
        response['api']['api_name'] = 'health'
        for item in response['value']:
            print '1111'
            print response['value'][item]
            response['value'][item] = response['value'][item]
            for item_2 in response['value'][item]:
示例#35
0
		except Exception, e:
			report = CommonLogger.log(
				error=e,
				source='task_engine',
				method='build_task'
				)
			return report
		post_process_time = time.time()
		print '### process task'
		if self.AxolTask.resource.local == False:
			try:
				self._process_task_response()
			except Exception, e:
				report = CommonLogger.log(
					error=e,
					source='task_engine',
					method='process_task_response'
					)
				return report
		print '### health'
		if self.AxolTask.source == 'health':
			try:
				self.AxolTask.resource.notification_threshold(
					AxolTask=self.AxolTask
					)
			except Exception, e:
				report = CommonLogger.log(
					error=e,
					source='task_engine',
					method='notification_threshold'
					)
示例#36
0
 print '### build task'
 try:
     self._build_task(roledefs=roledefs, data=new_data_object)
 except Exception, e:
     report = CommonLogger.log(error=e,
                               source='task_engine',
                               method='build_task')
     return report
 post_process_time = time.time()
 print '### process task'
 if self.AxolTask.resource.local == False:
     try:
         self._process_task_response()
     except Exception, e:
         report = CommonLogger.log(error=e,
                                   source='task_engine',
                                   method='process_task_response')
         return report
 print '### health'
 if self.AxolTask.source == 'health':
     try:
         self.AxolTask.resource.notification_threshold(
             AxolTask=self.AxolTask)
     except Exception, e:
         report = CommonLogger.log(error=e,
                                   source='task_engine',
                                   method='notification_threshold')
         return report
 print '### post process'
 try:
     self.AxolTask.post_process()
示例#37
0
class ResourceCreateHealthMetrics(AxolResource):
    """docstring for ResourceGetProcessorUsage
	Must implement:
		_show_help()
		self.source = {keyword}
		self.local = Bool
		self.store = Bool
		self.profiler = Bool
		api_<name of your api>()
		calculate_new_fields()
		write_to_database()
	Optional:
		if self.store = True, write_to_database() function must be implemented
	"""
    required_post = {'role': (True, u's'), 'profile': (False, u's')}

    def __init__(self):
        super(ResourceCreateHealthMetrics, self).__init__()
        self.source = 'health'
        self.local = True
        self.store = True
        self.profiler = True
        self.sources = [
            'cpu', 'memory', 'disk', 'mean', 'deviation_pos', 'deviation_neg'
        ]
        self.thresholds = (0)

    def _show_help(self):
        return {
            'help': {
                'api': '/api/create_health_metrics',
                'method': 'POST',
                'required_data': {
                    'role': '<some role>',
                },
                'version': api
            }
        }

    @staticmethod
    @app.route('/api/create_health_metrics', methods=['GET', 'POST'])
    def api_create_health_metrics():
        if request.method == 'GET':
            return jsonify(ResourceCreateHealthMetrics()._show_help())
        try:
            data = CommonResource.handle_request(
                request=request,
                params=ResourceCreateHealthMetrics.required_post)
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='create_health_metrics',
                                      method='api_create_health_metrics-1')
            return jsonify(report)
        try:
            response = ResourceCreateHealthMetrics().create_async_job(
                data=data)
        except Exception, e:
            report = CommonLogger.log(error=e,
                                      source='create_health_metrics',
                                      method='api_create_health_metrics-2')
            return jsonify(report)