Example #1
0
def heartbeat_2_director():
    print du.get_current_date_string(), '->发送心跳到指挥中心'
    import psutil
    try:
        time.sleep(1)

        cpu_usage_list = []
        cpu_info = hu.CPUinfo()
        cpu_usage = psutil.cpu_percent(interval=2, percpu=True)
        # print cpu_usage
        count = 1
        cpu_cores = len(cpu_usage) / len(cpu_info)
        import math
        fre = 0.0
        for per in cpu_usage:
            if count % cpu_cores == 0:
                # print 'fre:', fre
                cpu_usage_list.append({
                    'physical_id': count / cpu_cores - 1,
                    'cpu_usage': round(fre / cpu_cores, 1)
                })
                fre = 0.0
            else:
                fre += per
            count += 1

        mem_usage = int(psutil.virtual_memory().percent)
        disk_usage = int(psutil.disk_usage('/').free / 1024 / 1024 /
                         1024)  # 单位GB

        headers = {
            'Src-Node': SRC_NODE,
            'Src-Center': SRC_CENTER_ID,
            'Content-Type': 'application/json',
            'Channel-Tpye': 'JCQ',
            'User-Agent': CENTER_USER_AGENT,
            'X-Forwarded-For': detect_center_host
        }

        command_data = json.dumps(
            {
                'mem': mem_usage,
                'cpu': cpu_usage_list,
                'disk': disk_usage,
                'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            },
            ensure_ascii=False).encode('utf-8')

        # pu.pretty_print(command_data)

        sender.send_director(send_director_A + 'heartbeat', SRC_CENTER_ID,
                             "CENTER_HEARTBEAT", headers, command_data)

    except Exception:
        traceback.print_exc()
Example #2
0
def write_center_status_to_business_disposal():
    print du.get_current_date_string(), '->写管理中心状态到业务处置文件'
    import psutil
    try:
        # 生成业务处置系统所需文件
        if config.const.UPLOAD_BUSINESS_DISPOSAL:
            time.sleep(1)

            cpu_usage_list = []
            cpu_info = hu.CPUinfo()
            cpu_usage = psutil.cpu_percent(interval=2, percpu=True)
            # print cpu_usage
            count = 1
            cpu_cores = len(cpu_usage) / len(cpu_info)
            import math
            fre = 0.0
            for per in cpu_usage:
                if count % cpu_cores == 0:
                    # print 'fre:', fre
                    cpu_usage_list.append({
                        'physical_id':
                        count / cpu_cores - 1,
                        'cpu_usage':
                        round(fre / cpu_cores, 1)
                    })
                    fre = 0.0
                else:
                    fre += per
                count += 1

            mem_usage = int(psutil.virtual_memory().percent)
            disk_usage = int(psutil.disk_usage('/').free / 1024 / 1024 /
                             1024)  # 单位GB

            command_data = json.dumps(
                {
                    'mem': mem_usage,
                    'cpu': cpu_usage_list,
                    'disk': disk_usage,
                    'time': time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime())
                },
                ensure_ascii=False).encode('utf-8')

            handle_data_type = 'center_status'
            file_dir = os.path.join(config.const.DISPOSAL_DIR, 'status')
            file_name = 'center_status_' + str(int(time.time())) + '_' + str(1)
            sender.send_business_disposal(file_dir, file_name,
                                          CENTER_USER_AGENT, handle_data_type,
                                          command_data)
    except Exception:
        traceback.print_exc()
Example #3
0
def record_event():
    try:
        print du.get_current_date_string(), '##开始检查在线状态'
        device_info = Detector.objects.all()
        if device_info.exists():
            for device in device_info:
                old_online_status = device.is_online
                if (du.get_current_time() - (device.heartbeat_time if device.heartbeat_time is not None else (du.get_current_time() - timedelta(minutes=over_time_minute+1)))) > timedelta(minutes=over_time_minute) \
                        and (du.get_current_time() - (device.last_warning_time if device.last_warning_time is not None else (du.get_current_time() - timedelta(minutes=over_time_minute+1)))) > timedelta(minutes=over_time_minute):
                    print '####设置%s状态为离线' % device.device_id
                    Detector.objects.filter(id=device.id).update(
                        is_online=False)
                    if old_online_status:
                        online_event = {
                            'device_id': device.device_id,
                            'event': '离线',
                            'time': du.get_current_date_string()
                        }
                        serialize = DetectorOnlineEventSerializer(
                            data=online_event)
                        if serialize.is_valid():
                            serialize.save()
                            print '####device_id:', device.device_id, '保存离线事件'
                        else:
                            print '####device_id:', device.device_id, '保存离线事件', serialize.errors
                        center_report_detector_running_status(
                            device_id=device.device_id, device_is_online=0)
                else:
                    print '设置%s状态为在线' % device.device_id
                    Detector.objects.filter(id=device.id).update(
                        is_online=True)
                    if not old_online_status:
                        online_event = {
                            'device_id': device.device_id,
                            'event': '上线',
                            'time': du.get_current_date_string()
                        }
                        serialize = DetectorOnlineEventSerializer(
                            data=online_event)
                        if serialize.is_valid():
                            serialize.save()
                            print '####device_id:', device.device_id, '保存上线事件'
                        else:
                            print '####device_id:', device.device_id, '保存上线事件', serialize.errors
                        center_report_detector_running_status(
                            device_id=device.device_id, device_is_online=1)

        print '##检查在线状态完毕'
    except Exception as e:
        print e.message, e.args
Example #4
0
def record_online_event(device_id):
    device_info = Detector.objects.filter(device_id=device_id)
    if device_info.exists():
        if not device_info[0].is_online:
            print '记录重新上线事件'
            online_event = {
                'device_id': device_info[0].device_id,
                'event': '上线',
                'time': du.get_current_date_string()
            }
            serialize_data = DetectorOnlineEventSerializer(data=online_event)
            if serialize_data.is_valid():
                serialize_data.save()
            else:
                print 'device_id:', device_info[
                    0].device_id, '保存上线事件', serialize_data.errors
            center_report_detector_running_status(
                device_id=device_info[0].device_id, device_is_online=1)
Example #5
0
def center_report_detector_running_status(device_id=None, device_is_online=1):
    try:
        if not (config.const.UPLOAD_DIRECTOR
                and check_global_director_connection()):
            return

        if device_id is None:
            return
        else:
            device_info = Detector.objects.filter(device_id=device_id)
        if device_info.exists():
            for device in device_info:
                run_status_info = SystemRunningStatus.objects.filter(
                    device_id=device.device_id).order_by('-id')[0:1]
                if run_status_info.exists():
                    serialize_data = serialize('json',
                                               run_status_info,
                                               fields=('cpu', 'mem', 'disk',
                                                       'time', 'plug_stat',
                                                       'did'))
                    data_list = json.loads(serialize_data)
                    run_data = data_list[0]['fields']
                    run_data['cpu'] = json.loads(run_data['cpu'])
                    run_data['plug_stat'] = json.loads(run_data['plug_stat'])
                    run_data['time'] = run_data['time'].replace('T', ' ')
                else:
                    run_data = {
                        'cpu': [],
                        'mem': 0,
                        'disk': 0,
                        'time': du.get_current_date_string(),
                        'plug_stat': [],
                        'did': 1
                    }
                run_data['is_online'] = device_is_online

                command_data = json.dumps(run_data,
                                          ensure_ascii=False).encode('utf-8')
                common_header = {
                    'Channel-Type':
                    'JCQ',
                    'Msg-Type':
                    'status',
                    'Source-Type':
                    'STATUS_JCQ',
                    'BusinessData-Type':
                    'JCQ_STATUS_SYSTEM',
                    'Data-Type':
                    'msg',
                    'Task-Type':
                    '',
                    'Src-Node':
                    director_config.SRC_NODE,  # 源地区,用于指名产生告警的地区,管理中心的上级指挥节点
                    'Src-Center':
                    director_config.
                    SRC_CENTER_ID,  # 用于指名产生告警的控制节点或设备,一般指检测器管理中心编号
                    'User-Agent':
                    device.device_id + '/' + device.soft_version + '(iie)',
                    'Capture-Date':
                    datetime.datetime.strptime(
                        run_data['time'],
                        '%Y-%m-%d %H:%M:%S').strftime('%a, %d %b %Y %H:%M:%S'),
                    'Content-Type':
                    'application/json',
                    'version':
                    '1.0',
                    # 'Cookie': 'unknown',
                    'X-Forwarded-For':
                    director_config.detect_center_host,
                    'Src-Device':
                    device.device_id
                }
                ccd.upload_json_2_director_of_detector(
                    common_header, {'device_id': device.device_id},
                    command_data,
                    'JCQ_STATUS_SYSTEM',
                    async_level=1)
    except:
        traceback.print_exc()
def send_register_request(url=dc.send_director_A + 'reg',
                          src_center_id=dc.SRC_CENTER_ID,
                          center_serial=dc.CENTER_SERIAL,
                          src_node=dc.SRC_NODE,
                          src_ip=dc.director_host,
                          ip_whitelist=[dc.director_host, '172.17.0.1'],
                          retract=0):
    try:
        pu.print_format_header('管理中心发起注册', retract=retract)

        headers = {
            'Src-Node': src_node,
            'Src-Center': src_center_id,
            'Content-Type': 'application/json',
            'Channel-Tpye': 'JCQ',
            'User-Agent': dc.CENTER_USER_AGENT,
            'X-Forwarded-For': dc.detect_center_host
        }

        register_data = get_center_data()

        register_data['center_id'] = src_center_id
        register_data['center_ip'] = dc.detect_center_host
        register_data['center_serial'] = center_serial
        register_data['src_node'] = src_node
        register_data['src_ip'] = src_ip
        register_data['ip_whitelist'] = json.dumps(ip_whitelist)
        # del copy_data['access_time']
        register_data['register_time'] = du.get_current_date_string()
        register_data['id'] = 1

        # pretty_print(register_data)
        management_center = ManagementCenterInfo.objects.filter(
            center_id=dc.SRC_CENTER_ID)
        if not management_center.exists():
            ManagementCenterInfo.objects.all().delete()
            ManagementCenterInfo.objects.create(**register_data)
            # serializer = ManagementCenterInfoSerializer(data=register_data)
            # if serializer.is_valid():
            #     serializer.save()
            # else:
            #     print 'save management center', serializer.errors
        else:
            del register_data['register_time']
            management_center.update(**register_data)

        management_center = ManagementCenterInfo.objects.filter(
            center_id=dc.SRC_CENTER_ID)
        data = serialize('json',
                         management_center,
                         fields=('center_id', 'soft_version', 'device_ca',
                                 'organs', 'address', 'address_code',
                                 'contact', 'mem_total', 'interface',
                                 'cpu_info', 'disk_info'))  # 序列化
        list_data = json.loads(data)
        register_data = list_data[0]['fields']
        register_data['cpu_info'] = json.loads(register_data['cpu_info'])
        register_data['disk_info'] = json.loads(register_data['disk_info'])
        register_data['interface'] = json.loads(register_data['interface'])
        register_data['contact'] = json.loads(register_data['contact'])

        print "register_data:", pu.pretty_print_format(register_data)

        r = requests.post(url, data=json.dumps(register_data), headers=headers)
        # pu.print_with_retract(r.status_code, retract + 1)  # 响应码
        pu.print_with_retract(r.headers, retract + 1)  # 响应头
        pu.print_with_retract(r.text.encode('utf-8'), retract + 1)  # 响应消息正文

        result = json.loads(r.text.encode('utf-8'))

        center_info = ManagementCenterInfo.objects.filter(
            center_id=dc.SRC_CENTER_ID)
        if r.status_code == 200:  # (0:注册成功;1:注册失败;2:注册未审核)  #  (0: 认证成功  1:认证失败 2: 未认证)
            # if result["msg"] != u'该管理中心的已存在':
            center_info.update(center_status=2,
                               register_frequency=F('register_frequency') + 1,
                               register_status=2,
                               register_fail_reason='未审核',
                               auth_frequency=0,
                               auth_status=2,
                               auth_fail_reason='未认证',
                               cookie=None)
        elif result['msg'] == u'该管理中心的已存在':
            if center_info[0].register_status == 0 and center_info[
                    0].auth_status == 0:  # 管理中心主动重置与指挥的连接状态
                center_info.update(register_time=du.get_current_time(),
                                   register_frequency=F('register_frequency') +
                                   1)
                send_auth_login_request()
        config.const.DIRECTOR_VERSION = True
        config.const.UPLOAD_DIRECTOR = True

        pu.print_format_tail('管理中心发起注册', retract=retract)
        return result
    except:
        traceback.print_exc()