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
<?php
namespace console\controllers;
use yii\console\Controller;
use common\service\es\Elastic;
class IpExceptionController extends Controller
{
public function actionIndex()
{
$now = time();
$elastic = new Elastic('106.15.39.94:9200');
$params = [
'index' => 'bwallet_access',
'type' => 'doc',
'body' => [
"size" => 0,
"aggs" => [
"ips" => [
"terms" => [
"field" => "clientip.keyword",
"size" => 200,
"order" => [
"_count" => "desc"
]
],
"aggs" => [
"request" => [
"significant_terms" => [
"field" => "request.keyword",
"size" => 10,
]
]
]
]
],
"query" => [
"bool" => [
"must" => [
[
"range" => [
"@timestamp" => [
'gte' => ($now - 300) * 1000,
'lt' => $now * 1000,
"format" => "epoch_millis"
]
]
]
]
],
]
]
];
$elastic->connect();
$response = $elastic->search($params);
$hits = $response['hits'] ?? null;
$total = $hits['total'];
if (empty($total)) {
return false;
}
$buckets = $response['aggregations']['ips']['buckets'] ?? null;
if (empty($buckets)) {
return false;
}
$redis_ticker = \Yii::$app->redis_es;
$limit = \Yii::$app->params['api_ip_limit']['limit'];
$white_list = \Yii::$app->params['api_ip_limit']['white_list'];
foreach ($buckets as $key => $val) {
if (in_array($val['key'], $white_list)) continue;
if ($val['doc_count'] > $limit){
foreach ($val['request']['buckets'] as $bucket) {
$redis_ticker->hmset($val['key'], $bucket['key'], $bucket['doc_count']);
}
}
}
return false;
}
}