예제 #1
0
    def post(self, *args, **kwargs):
        ###文件保存到本地
        # Base_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        # upload_path = '{}/static'.format(Base_DIR)
        # file_metas = self.request.files.get('file', None)  # 提取表单中‘name’为‘file’的文件元数据
        # ret = {'result': 'OK'}
        # if not file_metas:
        #     ret['result'] = 'Invalid Args'
        #     return ret
        #
        # for meta in file_metas:
        #     filename = meta['filename']
        #     print('filename---->', filename)
        #     file_path = os.path.join(upload_path, filename)
        #     with open(file_path, 'wb') as up:
        #         up.write(meta['body'])
        #
        # self.write(json.dumps(ret))

        ###文件保存到OSS
        ###获取OSS的配置
        cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
        if cache_config_info:
            config_info = convert(cache_config_info)
        else:
            return self.write(dict(code=-1, msg='【系统管理】-【系统配置】-【存储配置】中没有检测到OSS配置信息'))

        file_metas = self.request.files.get('file', None)  # 提取表单中‘name’为‘file’的文件元数据

        if not file_metas:
            return self.write(dict(code=-2, msg='没有文件数据'))

        for meta in file_metas:
            filename = meta['filename']
            # print('filename---->', filename)
            file_data = meta['body']
            oss_data = {
                'STORAGE_KEY_ID': config_info.get('STORAGE_KEY_ID'),
                'STORAGE_KEY_SECRET': config_info.get('STORAGE_KEY_SECRET'),
                'STORAGE_REGION': config_info.get('STORAGE_REGION'),
                'STORAGE_NAME': config_info.get('STORAGE_NAME'),
                'STORAGE_PATH': 'fault'  # https://opendevops.oss-cn-shanghai.aliyuncs.com/fault/xxx.pdf
            }
            #
            # obj = OSSApi(
            #     oss_data.get('STORAGE_KEY_ID'), 'xxxx',
            #     oss_data.get('STORAGE_REGION'),
            #     oss_data.get('STORAGE_NAME'), oss_data.get('STORAGE_PATH'))
            # obj.setObj(filename, file_data)
            try:
                obj = OSSApi(
                    oss_data.get('STORAGE_KEY_ID'), oss_data.get('STORAGE_KEY_SECRET'),
                    oss_data.get('STORAGE_REGION'),
                    oss_data.get('STORAGE_NAME'), oss_data.get('STORAGE_PATH'))
                obj.setObj(filename, file_data)
            except Exception as e:
                return self.write(dict(code=-1, msg='上传失败,请检查OSS配置'))


        self.write(dict(code=0, msg="上传成功"))
예제 #2
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        alerts = data.get('alerts')  # 获取AlertManager POST报警数据
        #alerts = [{'status': 'firing', 'labels': {'alertname': 'Node主机CPU利用率过高', 'instance': '172.16.1.53:9100', 'prometheus': 'monitoring/k8s', 'severity': '严重'}, 'annotations': {'detail': '172.16.1.53:9100: CPU利用率过高于75% (当前值: 92.11666666667345)', 'summary': '172.16.1.53:9100: CPU利用率过高'}, 'startsAt': '2019-03-18T05:34:54.025953211Z', 'endsAt': '0001-01-01T00:00:00Z', 'generatorURL': 'http://prometheus-k8s-1:9090/graph?g0.expr=100+-+%28avg+by%28instance%29+%28irate%28node_cpu_seconds_total%7Bjob%3D%22node-exporter%22%2Cmode%3D%22idle%22%7D%5B5m%5D%29%29+%2A+100%29+%3E+75&g0.tab=1'}]
        for alerts_data in alerts:
            labels = alerts_data.get('labels')
            alert_name = labels.get('alertname')
            print('alert_name---->', alert_name)
            cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
            if cache_config_info:
                config_info = convert(cache_config_info)
            else:
                config_info = configs['email_info']

            emails_list = redis_conn.hvals(alert_name)
            print('Email_list----->', emails_list)
            sm = SendMail(
                mail_host=config_info.get(const.EMAIL_HOST),
                mail_port=config_info.get(const.EMAIL_PORT),
                mail_user=config_info.get(const.EMAIL_HOST_USER),
                mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                mail_ssl=True
                if config_info.get(const.EMAIL_USE_SSL) == '1' else False)
            ### 如果没有redis没有配置
            if not emails_list:
                # print(configs.get('default_email'))[0]  #元祖类型
                sm.send_mail(
                    configs.get('default_email')[0], alert_name,
                    alerts_data['annotations']['detail'])
                # print('msg=',alerts_data['annotations']['detail'])
                return self.write(dict(code=-1, msg="没有匹配到规则"))

            ### 默认发送邮件
            sm.send_mail(",".join(emails_list), alert_name,
                         alerts_data['annotations']['detail'])

            # 严重警告发短信
            if labels.get('severity') == "严重":
                if not configs.get('sign_name') or not configs.get(
                        'template_code'):
                    sm.send_mail(configs.get('default_email'), alert_name,
                                 '请配置短信的sign_name和template_code')
                else:
                    phone_numbers = redis_conn.hkeys(alert_name)
                    # 发送内容
                    params = {"msg": alerts_data['annotations']['detail']}
                    sms = SendSms(config_info.get(const.SMS_REGION),
                                  config_info.get(const.SMS_DOMAIN),
                                  config_info.get(const.SMS_PRODUCT_NAME),
                                  config_info.get(const.SMS_ACCESS_KEY_ID),
                                  config_info.get(const.SMS_ACCESS_KEY_SECRET))

                    sms.send_sms(phone_numbers=",".join(phone_numbers),
                                 template_param=params,
                                 sign_name=configs.get('sign_name')[0],
                                 template_code=configs.get('template_code')[0])

        return self.write(dict(code=0, msg="发送成功", data=alerts))
예제 #3
0
    def get(self, *args, **kwargs):
        """从redis获取阿里云OSS基本信息"""
        cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)

        if cache_config_info:
            config_info = convert(cache_config_info)

            if not config_info['STORAGE_REGION'] and not config_info['STORAGE_REGION']:
                return self.write(dict(code=-1, msg='没有发现OSS配置信息'))

            oss_info = {
                'STORAGE_REGION': config_info.get('STORAGE_REGION'),
                'STORAGE_NAME': config_info.get('STORAGE_NAME')
            }
            self.write(dict(code=0, msg="获取成功", data=oss_info))
        else:
            self.write(dict(code=-2, msg="没有在redis缓存发现配置信息"))