Passed
Pull Request — master (#235)
by John
05:34
created

Monitor   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 47
c 1
b 0
f 1
dl 0
loc 75
rs 10
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A check() 0 24 6
A __construct() 0 3 1
A ping() 0 37 3
1
<?php
2
namespace App\Babel\Extension\noj;
3
4
use App\Babel\Monit\MonitorBase;
5
use App\Models\OJModel;
6
use App\Models\JudgerModel;
7
use Exception;
8
9
class Monitor extends MonitorBase
10
{
11
    public $ocode="noj";
12
    public $oid=null;
13
14
    public function __construct()
15
    {
16
        $this->oid=OJModel::oid($this->ocode);
17
    }
18
19
    public function check()
20
    {
21
        $judgerModel=new JudgerModel();
22
        $serverList=$judgerModel->fetchServer($this->oid);
23
        foreach ($serverList as $server) {
24
            if ($server["available"]==0) {
25
                continue;
26
            }
27
28
            $serverURL="http://".$server["host"].":".$server["port"];
29
            try {
30
                $pong=$this->ping($serverURL.'/ping', $server["port"], hash('sha256', $server["token"]));
31
            } catch (Exception $exception) {
32
                $this->updateStatus($server["jsid"], 1);
33
                continue;
34
            }
35
36
            if (empty($pong)) {
37
                $this->updateStatus($server["jsid"], 1);
38
                continue;
39
            }
40
41
            if ($pong["status_code"]==200) {
42
                $this->updateStatus($server["jsid"], 0);
43
            }
44
        }
45
    }
46
47
    private function ping($url, $port, $token)
48
    {
49
        $curl=curl_init();
50
51
        if ($curl===false) {
52
            return [];
53
        }
54
55
        curl_setopt_array($curl, array(
56
            CURLOPT_PORT => $port,
57
            CURLOPT_URL => $url,
58
            CURLOPT_RETURNTRANSFER => true,
59
            CURLOPT_ENCODING => "",
60
            CURLOPT_MAXREDIRS => 10,
61
            CURLOPT_TIMEOUT => 30,
62
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
63
            CURLOPT_CUSTOMREQUEST => "POST",
64
            CURLOPT_POSTFIELDS => "",
65
            CURLOPT_HTTPHEADER => array(
66
                "Content-Type: application/json",
67
                "X-Judge-Server-Token: ".$token,
68
                "cache-control: no-cache"
69
            ),
70
        ));
71
72
        $response=curl_exec($curl);
73
        $err=curl_error($curl);
74
        $httpCode=curl_getinfo($curl, CURLINFO_HTTP_CODE);
75
76
        curl_close($curl);
77
78
        if ($err) {
79
            return [];
80
        } else {
81
            return [
82
                "status_code"=>$httpCode,
83
                "body"=>json_decode($response)
84
            ];
85
        }
86
    }
87
}
88