summaryrefslogtreecommitdiff
path: root/src/main.php
blob: 60779e5fd34c63d8738704c8372b79e3a8bb633e (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
<?php

require __DIR__.'/init.php';

if ($argc < 2) {
    echo <<<EOF
Usage: {$argv[0]} COMMAND

Commands:
    test
    hello
    createfile

EOF;
    exit;
}

$cmd = $argv[1];
$func = "cmd_{$cmd}";
if (!function_exists($func)) {
    echo red("command '".$cmd."' is not implement")."\n";
    exit(1);
}

call_user_func($func);


/** Commands */

function cmd_test() {
    // MySQL
    try {
        $db = getMySQL();
        $jobs_count = $db->result($db->query("SELECT COUNT(*) FROM ".JOBD_TABLE));
    } catch (Exception $e) {
        echo red("MySQL connection failed")."\n";
        exit(1);
    }
    echo green("MySQL OK")."\n";

    // jobd
    try {
        $jobd = getJobdMaster();
        $status = $jobd->status(true);
        $workers_count = count($status->getData()['workers']);
        if ($workers_count == 2) {
            echo green("jobd-master and jobd OK");
        } else {
            $message = "jobd-master OK, but ";
            $message .= $workers_count == 1 ? "only 1 worker is connected" : "no workers are connected";
            echo yellow($message);
        }
        echo "\n";
    } catch (Exception $e) {
        echo red("jobd-master connection failed: ".$e->getMessage())."\n";
        exit(1);
    }
}

function cmd_hello() {
    $myname = input('Enter your name: ');
    try {
        $job_ids = [];
        $job_server_map = [];

        for ($server = 1; $server <= 2; $server++) {
            $id = jobs::manual(job_target::high($server), jobs\Hello::class, ['name' => $myname]);
            $job_server_map[$id] = $server;
            $job_ids[] = $id;
        }

        $results = jobs::run($job_ids);
        foreach ($results as $job_id => $job_result) {
            $server = $job_server_map[$job_id];
            echo "> server {$server}:\n";
            if ($job_result->isFailed()) {
                echo red("failed")."\n";
            } else {
                echo green($job_result->getStdoutAsJSON()['response'])."\n";
            }
            echo "\n";
        }

    } catch (Exception $e) {
        echo red("error: ".$e->getMessage())."\n";
        exit(1);
    }
}

function cmd_createfile() {
    $file = input('Enter file name: ');
    jobs::add(job_target::any, jobs\CreateFile::class, ['file' => $file]);
}