summaryrefslogtreecommitdiff
path: root/getLog.py
blob: b85c750a1998069f266c74080db76d375fb4b5e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
#!/usr/bin/python3
# coding=utf-8
import copy
import time
import requests
import json
import ipaddress
import verify

class GetLog():    
    def get_log_schema(self, token, log_type, api_host, vsys_id):
        # 修改完成后删除注释:将下方的security_event替换成变量
        headers = {'Content-Type': 'application/json', 'Authorization': token}
        url = api_host + "/v1/log/schema/" + log_type + "?vsys_id=" + str(vsys_id)
        response = requests.get(url, headers=headers, verify=False)
        assert response.status_code == 200
        log_schema = json.loads(response.text)
        log_schema = log_schema['data']['fields']
        log_schema = ",".join([field['name'] for field in log_schema])
        return log_schema
    
    def get_log_by_condition(self, token, ruleNum, start_time, end_time, test_pc_ip, create_policies_ids, condition, api_host, vsys_id):
        headers = {'Content-Type': 'application/json', 'Authorization': token}
        log_condition = {
            "page_no": 1,
            "page_size": 20,
            "source": "security_event",
            "columns": None,
            "start_time": "",
            "end_time": "",
            "filter": "",
            "vsys_id": 1
        }
        log_condition_dict = json.loads(json.dumps(log_condition))
        # 多次循环
        for i in range(ruleNum):
            policy_id = list(create_policies_ids[i].values())[0]
            fields = self.get_log_schema(token, "security_event", api_host, vsys_id)
            log_condition_dict['columns'] = fields
            log_condition_dict['start_time'] = start_time
            log_condition_dict['end_time'] = end_time
            log_condition_dict['vsys_id'] = vsys_id
            log_condition_dict['log_type'] = 'security_event'
            log_condition_dict['identifier_name'] = 'security-event-list'
            log_condition_dict['execution_mode'] = 'oneshot'
            # 从conditions中获取object_type判断是否存在subscriberid
            if len(condition["obj_condition_1"]) > 0 and condition["obj_condition_1"][0]["attribute_name"] == "ATTR_SUBSCRIBER_ID":
                log_filter = f"subscriber_id= 'test23' AND has(security_rule_list,{policy_id})"
                log_condition_dict['filter'] = log_filter
            else:
                log_filter = f"client_ip={test_pc_ip} AND has(security_rule_list,{policy_id})"
                log_condition_dict['filter'] = log_filter
                log_condition_dict['filter'] = log_condition_dict['filter'].replace(f"client_ip={test_pc_ip}", f"client_ip='{test_pc_ip}'")
            url = api_host + "/v1/log/query"
            # print(json.dumps(log_condition_dict))
            print(log_condition_dict)
            response = requests.post(url, headers=headers, json=log_condition_dict, verify=False)
            assert response.status_code == 200
            log_list = json.loads(response.text)
            # print(log_list)
            log_list = log_list['data']['result']
            log_index = i + 1
            log_query_params = condition['log_query_param_'+str(log_index)]
            if len(log_list) > 0 and len(log_query_params) > 0:
                for log in log_list:
                    for log_query_param in log_query_params:
                        print(log)
                        query_field_key = log_query_param['query_field_key']
                        query_value = log_query_param['query_value']
                        if query_field_key in log and log[query_field_key] == query_value:
                            log_reult = True
                        else:
                            log_reult = False
            elif len(log_list) == 0 and len(log_query_params) > 0:
                log_reult = False
            elif len(log_list) == 0 and len(log_query_params) == 0:
                # 此时代表不需要进行logs模块的校验,可能为security shunt动作或statistics,sc策略等
                log_reult = True
            # 当日志中出现false时,就跳出此循环,多次true才可以将result置为true
            if log_reult == False:
                break
        return log_reult

    def get_metric(self, token, ruleNum, start_time, end_time, create_policies_ids, condition, api_host, vsys_id):
        #请求接口查询metric
        headers = {'Content-Type': 'application/json', 'Authorization': token}
        url = api_host + "/v1/log/query"
        for i in range(ruleNum):
            policy_type = condition['policyType']
            if policy_type == 'security':
                dataset_identifier_name = "security-policy-rule-statistics"
            elif policy_type == 'pxy_intercept' or policy_type == 'pxy_manipulation':
                dataset_identifier_name = "proxy-policy-rule-statistics"
            elif policy_type == 'monitor':
                dataset_identifier_name = "monitor-policy-rule-statistics"
            policy_id = list(create_policies_ids[i].values())[0]
            hit_query_condition = {"identifier_name":dataset_identifier_name,"rule_id":"","start_time":"","end_time":"","vsys_id":1,"execution_mode": "oneshot","output_mode":"json", "interval":1}
            # hit_query_condition['rule_id'] = f"{policy_id}"
            hit_query_condition['rule_id'] = policy_id
            hit_query_condition['start_time'] = start_time
            hit_query_condition['end_time'] = end_time
            hit_query_condition['vsys_id'] = vsys_id
            print(json.dumps(hit_query_condition))
            response = requests.post(url, headers=headers, json=hit_query_condition, verify=False)
            assert response.status_code == 200
            response = json.loads(response.text)
            index = i + 1
            counter = condition['counters_'+str(index)]
            result_len = len(response['data']['result'])
            # 需要hits == 0时,则验证,验证通过metric置为true
            if 'hits' in counter and counter['hits'] == 0 and result_len == 0:
                metric_result = True
            elif 'hits' in counter and counter['hits'] == 'many' and result_len > 0:
                metric = response['data']['result'][0]
                print(metric)
                hits = metric['hits']
                if hits > 0:
                    metric_result = True
                else:
                    metric_result = False
            # 接口有返回值时,对接口的返回内容进行验证
            elif 'hits' in counter and result_len > 0:
                metric = response['data']['result'][0]
                for key,value in counter.items():
                    # 接口返回的统计是否与预期的一致
                    if key not in metric or metric[key] != value:
                        metric_result = False
                    else:
                        metric_result = True
            elif 'hits' not in counter:
                metric_result = True
            else:
                metric_result = False
            return metric_result

    def get_livechart_statistics(self, token, start_time, end_time, statistics_info, statistics_metircs_except, trex_ip_info, condition, host_api, vsys_id, alignment_period="PT1S"):
        """
        :param token:
        :param start_time:
        :param end_time:
        :param statistics_info:
        :param condition:
        :return:
        """
        # 请求接口查询statistics metric
        headers = {'Content-Type': 'application/json', 'Authorization': token}
        url = "{}/v1/log/query".format(host_api)
        # 重组请求体数据
        post_data_ori_json = """
        {
            "execution_mode":"oneshot",
            "query_type":"real_time",
            "start_time":"2023-11-24T02:55:40Z",
            "end_time":"2023-11-24T03:00:40Z",
            "alignment_period":"PT15S",
            "sql":"",
            "filter":"",
            "template_id":1051,
            "version":1,
            "chart_id":2705,
            "vsys_id":1,
            "rule_id":274147,
            "duration":1,
            "interval":1,
            "limit":10000,
            "output_mode":"json"
        }
        """
        post_data_ori_dict = json.loads(post_data_ori_json)
        # if statistics_info["chart_type"] == "table" or statistics_info["chart_type"]  == "bar":
        #     dataset_identifier_name = "statistics-rule-table-or-bar-chart-template"
        # elif statistics_info["chart_type"]  == "line":
        #     dataset_identifier_name = "statistics-rule-line-chart-template"
        # else:            #  = histogram
        #     dataset_identifier_name = "statistics-rule-histogram-chart-template"
        #post_data_ori_dict["dataset_identifier_name"] = dataset_identifier_name
        post_data_ori_dict["start_time"] = start_time
        post_data_ori_dict["end_time"] = end_time
        post_data_ori_dict["rule_id"] = statistics_info["rule_id"]
        post_data_ori_dict["template_id"] = statistics_info["template_id"]
        post_data_ori_dict["chart_id"] = statistics_info["chart_id"]
        post_data_ori_dict["version"] = statistics_info["version"]
        post_data_ori_dict["alignment_period"] = alignment_period
        post_data_ori_dict["vsys_id"] = vsys_id
        post_data_ori_dict["sql"] =statistics_info["sql"]
        # print("statistics metric请求体数据:")
        #print(post_data_ori_dict)
        #print(headers)
        response = requests.post(url, json=post_data_ori_dict, headers=headers, verify=False)
        #assert response.status_code == 200
        r_dict = response.json()
        print("statistics metric结果数据:")
        print(r_dict)
        if r_dict["code"] != 200:
            print("statistics metric 查询失败")
            return [333, "The statistics metric API query failed. Procedure"]
        else:    # 返回正常结果
            if r_dict["data"]["result"] == []:   # 为空
                print("########statistics metric 没有查询到结果###############")
                # 对应session方式和fqdn category需要另行处理
                metrics_columns = condition["profile_condition_1"][0]["chart_list"][0]["metrics"][0]["source_columns"].lower()
                try:
                    dimension_columns = condition["profile_condition_1"][0]["chart_list"][0]["dimensions"][0]["source_columns"][0].lower()
                except:
                    dimension_columns = "no_dimensions"
                if metrics_columns == "new_in_sessions" or metrics_columns == "new_out_sessions" or dimension_columns == "fqdn_category":
                    return [333, "passthrough"]
                return [333, "statistics metric No result was found"]
            else:     # 提取结果,并断言
                metric_result = False  # 默认
                result_list_source = r_dict["data"]["result"]
                #print(result_list_source)
                result_list = []
                for _ in copy.deepcopy(result_list_source):    # 将key转成小写,  ***且将key中空格替换为下划线****
                    #result_list.append({k.lower():v for k, v in _.items()})
                    tmp_dict = {}
                    for k, v in _.items():
                        k_0 = "_".join(k.lower().split())    # 将key变为小写且使用下划线连接
                        tmp_dict[k_0] = v
                    result_list.append(tmp_dict)
                #print(result_list)
                statistics_value = 0
                if statistics_info["chart_type"] == "line" or statistics_info["chart_type"] == "table" or statistics_info["chart_type"] == "bar":
                    print(f'{statistics_info["chart_type"]}>>断言对比...')
                    print(statistics_info)
                    statistics_value = copy.deepcopy(result_list[0])
                    # 将列表中metric值设置为0
                    for k, v in statistics_value.items():
                        if isinstance(v, int):
                            statistics_value[k] = 0
                    # 遍历result结果,将metric值累加并存储到statistics_value;因为流量单一,只能统计第一个计算值
                    print(result_list)
                    tmp_list_1 = []   # 下面for..提取值使用
                    for result_index in range(len(result_list)):
                        if "session_identifier_sketch" in result_list[0].keys():     # session_identifier_sketch 需要单独处理
                            for k, v in result_list[result_index].items():
                                if isinstance(v, int):
                                    if v != 0:
                                        tmp_list_1.append(v)   # 将不等于0的数值添加到列表中,为了计算平均数
                        else:     # 其它的取值方式
                            for k, v in result_list[result_index].items():
                                if isinstance(v, int):
                                    statistics_value[k] += v
                            if  "client_ip_matched_objects".lower() in result_list[0].keys() or "server_ip_matched_objects".lower() in result_list[0].keys() or "websketch_categories".lower() in result_list[0].keys():
                                break
                    if "session_identifier_sketch" in result_list[0].keys() or "client_ip_sketch" in result_list[0].keys() or "server_ip_sketch" in result_list[0].keys():  # session_identifier_sketch 需要单独处理
                        sum_1 = 0
                        for i in range(1, len(tmp_list_1) - 1):  # 去掉首位两个数计算平均数
                            sum_1 += tmp_list_1[i]
                        avg_1 = sum_1 / (len(tmp_list_1) - 2)
                        for k, v in result_list[0].items():  # 取得session_indentifier_sketch的值
                            if isinstance(v, int):
                                statistics_value[k] = avg_1
                    print("TSG实际查询到的结果数据:\n{}".format(statistics_value))
                    # 重组需要断言使用的key列表
                    assert_key_list = []
                    for k, v in statistics_value.items():
                        if isinstance(v, int) or isinstance(v, float):
                            assert_key_list.append(k)
                    # 开始判断key的正确性
                    for i in range(len(assert_key_list)):
                        metric_results = self.assert_livechart_statistics(statistics_info["chart_type"], assert_key_list[i], statistics_value, statistics_metircs_except, trex_ip_info)  # 判断正确调用函数
                        metric_result = metric_results[0]
                        if metric_result == False:
                            print("断言时失败:断言内容为:{}".format(assert_key_list[i]))
                            break
                elif statistics_info["chart_type"] == "histogram":
                    print("histogram图表暂不统计结果")
                    metric_results = [True, ""]
                return metric_results

    def assert_livechart_statistics(self, chart_type, assert_key, statistics_value, statistics_metircs_except, trex_ip_info):
        metric_result = False
        failure_reason = "<<<<<<<<<< 结果失败 >>>>>>>>>>"
        success_result = "<<<<<<<<<< 结果通过 >>>>>>>>>>"
        failure_reason_info = ""
        failure_info_1 = ""
        failure_info_2= ""
        failure_info_3 = ""
        if chart_type == "line":
            print(f"流量回放预期结果总数:\n{statistics_metircs_except}")
            failure_info_1 = f"Total expected results for traffic playback:{statistics_metircs_except}"
            statistics_metircs_except_avg = {}     # 重组预期1秒粒度结果
            for k, v in statistics_metircs_except.items():
                if "bytes" in k:
                    statistics_metircs_except_avg[k] = int((v) / 1)    # 统计平均字节数
                else:
                    statistics_metircs_except_avg[k] = int(v / 1)
            if assert_key != "session_identifier_sketch" and assert_key != "client_ip_sketch" and assert_key != "server_ip_sketch":    # 除了这几个gauge,需要打印下信息
                print(f"流量回放结果按1秒粒度平均数:\n{statistics_metircs_except_avg}")
            failure_info_2 = f"Average number of traffic playback results by 1-second granularity:{statistics_metircs_except_avg}"
            print(assert_key)
            if assert_key == "bytes":
                if statistics_value[assert_key] > (statistics_metircs_except_avg["total_bytes"] - 10):    # 预期值减10,因为出现多个时间周期统计的结果实际值减小
                    print(success_result)
                    metric_result = True
            elif assert_key == "in_bytes" or assert_key == "out_bytes":
                print(assert_key)
                if (statistics_value[assert_key] > (statistics_metircs_except_avg["total_bytes_sent"] - 10)) or (statistics_value[assert_key] > (statistics_metircs_except_avg["total_bytes_received"] - 10)):
                    print(success_result)
                    metric_result = True
            elif assert_key == "new_c2s_flows" or assert_key == "new_s2c_flows" or assert_key == "sessions" or assert_key == "new_in_sessions" or assert_key == "new_out_sessions" or assert_key == "syn_pkts":
                if assert_key == "new_c2s_flows" or assert_key == "new_s2c_flows" or assert_key == "sessions":  # 双向流,两个方向都是一样的
                    if statistics_value[assert_key] == statistics_metircs_except_avg["total_syn_pkt"]:
                        print(success_result)
                        metric_result = True
                elif assert_key == "syn_pkts":
                    if statistics_value[assert_key] == (statistics_metircs_except_avg["total_syn_pkt"] * 2):
                        print(success_result)
                        metric_result = True
                elif assert_key == "new_in_sessions" or assert_key == "new_out_sessions":  # 区分方向
                    if statistics_value[assert_key] == statistics_metircs_except_avg["total_syn_pkt"] or statistics_value[assert_key] == 0:
                        print(success_result)
                        metric_result = True
            elif assert_key == "session_identifier_sketch" or assert_key == "client_ip_sketch" or assert_key == "server_ip_sketch":
                statistics_metircs_except_gauge = {}
                for k, v in statistics_metircs_except.items():
                    statistics_metircs_except_gauge["session_identifier_sketch"] = statistics_metircs_except["total_syn_pkt"]
                    # 计算ip个数,分析gauge的预期结果 active_sessions  unique_client_ips  unique_server_ips
                    unique_client_ips = self.diff_ip_count(trex_ip_info["clients_start"], trex_ip_info["clients_end"])
                    unique_server_ips = self.diff_ip_count(trex_ip_info["servers_start"], trex_ip_info["servers_end"])
                    sessions_count = statistics_metircs_except["total_syn_pkt"]
                    if sessions_count < unique_client_ips:
                        unique_client_ips = sessions_count
                    if sessions_count < unique_server_ips:
                        unique_server_ips = sessions_count
                    statistics_metircs_except_gauge["client_ip_sketch"] = unique_client_ips
                    statistics_metircs_except_gauge["server_ip_sketch"] = unique_server_ips
                    print(f"流量回放结果按1秒粒度的Gauge:\n{statistics_metircs_except_gauge}")
                    if -3 < statistics_value[assert_key] - statistics_metircs_except_gauge[assert_key] < 3:
                        print("<<<<<<<<<<statistics 结果正常>>>>>>>>>>")
                        metric_result = True
            else:
                print(f"遗漏断言的key:{assert_key}")
                metric_result = False
        elif chart_type == "histogram":
            metric_result = True
        else:    # table bar等二维图表
            print(f"流量回放结果总数:\n{statistics_metircs_except}")
            failure_info_1 = f"Total expected results for traffic playback:{statistics_metircs_except}"
            if assert_key == "bytes":
                if statistics_value[assert_key] == statistics_metircs_except["total_bytes"]:
                    print(success_result)
                    metric_result = True
            elif assert_key == "in_bytes" or assert_key == "out_bytes":
                if (statistics_value[assert_key] == statistics_metircs_except["total_bytes_sent"]) or (statistics_value[assert_key] == statistics_metircs_except["total_bytes_received"]):
                    print(success_result)
                    metric_result = True
            elif assert_key == "new_c2s_flows" or assert_key == "new_s2c_flows" or assert_key == "sessions" or assert_key == "new_in_sessions" or assert_key == "new_out_sessions" or assert_key == "syn_pkts":
                if assert_key == "new_c2s_flows" or assert_key == "new_s2c_flows" or assert_key == "sessions":    # 双向流,两个方向都是一样的
                    if statistics_value[assert_key] == statistics_metircs_except["total_syn_pkt"]:
                        print(success_result)
                        metric_result = True
                elif assert_key == "syn_pkts":
                    if statistics_value[assert_key] == (statistics_metircs_except["total_syn_pkt"] * 2):
                        print(success_result)
                        metric_result = True
                elif assert_key == "new_in_sessions" or assert_key == "new_out_sessions":    # 区分方向
                    if statistics_value[assert_key] == statistics_metircs_except["total_syn_pkt"] or statistics_value[assert_key] == 0:
                        print(success_result)
                        metric_result = True
            else:
                print(f"遗漏断言的key:{assert_key}")
                failure_info_3 = f"key for missing assertions:{assert_key}"
                metric_result = False
        if metric_result == False:
            print(failure_reason)
            actual_result = "Total actual results:{statistics_value}"
            failure_reason_info = "{}{}{}.{}".format(failure_info_1, failure_info_2, failure_info_3, actual_result)
        return metric_result, failure_reason_info

    def get_sc_metric(self, token, start_time, end_time, sc_info, sc_expected_metric, active_dest_ips_list, host_api,vsys_id):
        # 请求接口查询sc metric
        headers = {'Content-Type': 'application/json', 'Authorization': token}
        url = "{}/v1/log/query".format(host_api)
        # 重组请求体数据
        post_data_ori_json = """
        {
            "execution_mode": "oneshot",
            "identifier_name": "service-chaining-policy-rule-statistics",
            "rule_id": "271039",
            "start_time": "2023-11-21T03:23:24Z",
            "end_time": "2023-11-30T07:39:49Z",
            "vsys_id": 1,
            "interval": 1,
            "limit": 10000,
            "output_mode": "json"
        }
        """
        # 重组请求体数据
        post_data_ori_dict = json.loads(post_data_ori_json)
        post_data_ori_dict["identifier_name"] = "service-chaining-policy-rule-statistics"
        post_data_ori_dict["start_time"] = start_time
        post_data_ori_dict["end_time"] = end_time
        post_data_ori_dict["rule_id"] = int(sc_info["rule_id"])
        post_data_ori_dict["vsys_id"] = vsys_id
        # print("sc metric请求体数据:")
        # print(post_data_ori_dict)
        response = requests.post(url, json=post_data_ori_dict, headers=headers, verify=False)
        r_dict = response.json()
        print("sc metric结果数据:")
        # print(r_dict)
        if r_dict["code"] != 200:
            print("service chaining metric query failed")
            return 444
        else:    # 返回正常结果
            if r_dict["data"]["result"] == []:   # 为空
                print("########service chaining metric is empty###############")
                return 333
            else:   #metric不为空时,验证返回结果
                metric_result = False  # 默认
                result_list = r_dict["data"]["result"]
                sc_value = copy.deepcopy(result_list[0])
                metric_result = self.assert_sc_metric(sc_info, sc_value, sc_expected_metric, active_dest_ips_list)
        # print(str(metric_result))
        return metric_result

    def assert_sc_metric(self, sc_info, sc_value, sc_expected_metric,active_dest_ips_list):
        metric_result = False
        failure_reason = "<<<<<<<<<<sc 结果失败>>>>>>>>>>"
        success_result = "<<<<<<<<<<sc 结果正常>>>>>>>>>>"
        if sc_info["targeted_traffic"] == "raw":
            byte_value = sc_expected_metric["total_bytes"]
            pkt_value = sc_expected_metric["total_packets"]
            lost_pkt = 3
            lost_byte = 192  # tcp三次握手的三个包的字节数和
            if sc_info["sf_method"] == "vxlan_g" and sc_info["sf_dest_ip"] in active_dest_ips_list:
                if sc_info["app_name_1"]:
                    pkt_value -= lost_pkt
                    byte_value -= lost_byte
                sc_expected_metric["total_bytes"] = byte_value + 50 * pkt_value
                if sc_info["type"] == 1:
                    if sc_value["sent_bytes"] == sc_value["received_bytes"] == sc_expected_metric["total_bytes"] and sc_value["sent_packets"] == sc_value["received_packets"] == pkt_value:
                        print(success_result)
                        metric_result = True
                    else:
                        metric_result = False
                elif sc_info["type"] == 2:
                    if sc_value["sent_bytes"] == sc_expected_metric["total_bytes"] and sc_value["sent_packets"] == pkt_value and sc_value["received_bytes"] == sc_value["received_packets"] == 0:
                        print(success_result)
                        metric_result = True
                    else:
                        metric_result = False
                else:
                    metric_result = False
            elif sc_info["sf_method"] == "layer2_switch":
                if sc_info["app_name_1"]:
                    pkt_value -= lost_pkt
                    byte_value -= lost_byte
                sc_expected_metric["total_bytes"] = byte_value + 4 * pkt_value
                if sc_info["type"] == 2:
                    if sc_value["sent_bytes"] == sc_expected_metric["total_bytes"] and sc_value["sent_packets"] == pkt_value and sc_value["received_bytes"] == sc_value["received_packets"] == 0:
                        print(success_result)
                        metric_result = True
                    else:
                        metric_result = False
                else:
                    metric_result = False
        elif sc_info["targeted_traffic"] == "decrypted":
            if sc_info["sf_method"] == "vxlan_g" and sc_info["sf_dest_ip"] in active_dest_ips_list:
                if sc_info["type"] == 1:
                    if sc_value["sent_bytes"] == sc_value["received_bytes"] and sc_value["sent_packets"] == sc_value["received_packets"]:
                        print(success_result)
                        metric_result = True
                    else:
                        metric_result = False
                elif sc_info["type"] == 2:
                    if sc_value["sent_bytes"] != 0 and sc_value["sent_packets"] != 0 and sc_value["received_bytes"] == sc_value["received_packets"] == 0:
                        print(success_result)
                        metric_result = True
                    else:
                        metric_result = False
                else:
                    metric_result = False
            elif sc_info["sf_method"] == "layer2_switch":
                if sc_info["type"] == 2 and len(sc_value) != 0:
                    if sc_value["sent_bytes"] != 0 and sc_value["sent_packets"] != 0 and sc_value["received_bytes"] == sc_value["received_packets"] == 0:
                        print(success_result)
                        metric_result = True
                    else:
                        metric_result = False
                else:
                    metric_result = False
        if metric_result == False:
            print(failure_reason)
        return metric_result

    def diff_ip_count(self, start_ip, end_ip):
        start_ip_obj = ipaddress.IPv4Address(start_ip)
        end_ip_obj = ipaddress.IPv4Address(end_ip)
        ip_count = int(end_ip_obj) - int(start_ip_obj) + 1
        return ip_count

# if __name__ == '__main__':
#     l = GetLog()
#     sc_info = {"sf_method":"vxlan","type":2}
#     assert_key = {}
#     sc_value = {
#         "sent_bytes": 260,
#         "received_bytes": 0,
#         "sent_packets": 5,
#         "received_packets": 0
#     }
#     trex_ip_info = {}
#     host_api = {}
#     sc_expected_metric =  {
#             "total_bytes" : 10,
#             "total_packets" : 5
#         }
#     l.assert_sc_metric(sc_info,sc_value,sc_expected_metric,trex_ip_info,host_api)
# if __name__ == '__main__':
#     test = GetLog()
#     counter = {"hits": 4824, "bytes":1547374}
#     metric = {"rule_id":251725,"hits":4824,"bytes":1547374}
#     metric_result = test.verify_metric(counter, metric)
#     print(metric_result)
# if __name__ == '__main__':
#     ipObject = get_log_by_condition()
#     time.sleep(3)
# if __name__ == '__main__':
#     api_host = "http://192.168.44.3"
#     v = verify.Verify()
#     username = "admin"
#     password = "admin"
#     v.encryptPwd(password, api_host)
#     token = v.login(username, api_host)
#     l = GetLog()
#     sc_info = {
#         'app_name_1': [

#         ],
#         'health_check_method': 'none',
#         'rule_id': 311524,
#         'sf_dest_ip': '2.2.2.57',
#         'sf_id': 2096,
#         'sf_method': 'vxlan_g',
#         'sff_id': 2090,
#         'targeted_traffic': 'raw',
#         'type': 1
#     }
#     sc_metric = {
#     'total_packets': 347,
#     'total_packets_sent': 97,
#     'total_packets_received': 250,
#     'total_bytes': 339823,
#     'total_bytes_sent': 5892,
#     'total_bytes_received': 333931,
#     'total_syn_pkt': 1
# }
#     assert_key = {}
#     start_time = "2023-12-11T08:16:46Z"
#     end_time = "2023-12-11T08:20:31Z"
#     l.get_sc_metric(token,start_time,end_time,sc_info,sc_metric,api_host)
#     test = GetLog()
#     log_dict = {
#                 "common_recv_time": "1698299472",
#                 "common_log_id": "84305355500406784",
#                 "common_client_ip": "5.183.148.25",
#                 "ssl_sni": "www.baidu.com"
#             }
    
#     log_query_params = {"query_field_key":"ssl_sni","query_value":"www.baidu.com"}
#     log_result = test.verify_log_list(log_dict, log_query_params)