IpExceptionController.php 2.69 KB
<?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;
    }
}