clivern/monkey

Apache CloudStack SDK in PHP。

1.1.1 2021-01-10 14:42 UTC

README

Apache CloudStack SDK in PHP。

Build Status License Latest Stable Version

安装

要使用 composer 安装此包,请使用以下命令

$ composer require clivern/monkey

此命令要求您全局安装了 Composer。

CloudStack 模拟器

安装 Docker

在 Ubuntu 上安装 docker。

$ apt-get update
$ sudo apt install docker.io

然后确保重启后可以启动

$ sudo systemctl enable docker

然后运行 CloudStack 模拟器。

$ docker pull cloudstack/simulator
$ docker run --name simulator -p 8080:8080 -d cloudstack/simulator
$ docker exec -ti simulator python /root/tools/marvin/marvin/deployDataCenter.py -i /root/setup/dev/basic.cfg

用法

将包添加为依赖项后,请阅读以下步骤

配置 CloudStack 凭据

include_once dirname(__FILE__) . '/vendor/autoload.php';

use Clivern\Monkey\Util\Config;

$config = new Config();
$config->addCloudStackServer("us_dc_clsk_01", [
    "api_url"   => "http://clsk_url.com:8080/client/api",
    "api_key"    => "api_key_here",
    "secret_key" => "secret_key_here"
]);

// OR

$config = new Config([
    "us_dc_clsk_01" => [
        "api_url"   => "http://clsk_url.com:8080/client/api",
        "api_key"    => "api_key_here",
        "secret_key" => "secret_key_here"
    ]
]);

// To use self-signed or invalid SSL for connecting to CloudStack

$config = new Config([
    "us_dc_clsk_01" => [
        "api_url"   => "https://clsk_url.com:8443/client/api",
        "api_key"    => "api_key_here",
        "secret_key" => "secret_key_here",
        "verify_ssl" => false
    ]
]);

// To Check if CloudStack Server Credentials Exists
$config->isCloudStackServerExists("us_dc_clsk_01"); // Return Boolean

// To Get CloudStack Server Credentials
$config->getCloudStackServer("us_dc_clsk_01"); // Return array & May be empty if not exist

// To Get All CloudStack Servers Credentials
$config->getCloudStackServers(); // Return Array

// To Remove CloudStack Server
$config->removeCloudStackServer("us_dc_clsk_01"); // Return Boolean

运行同步调用

为了运行同步调用,例如创建新用户,您需要检查 cloudstack api 以获取命令和所需的参数。首先让我们创建一个由于缺少参数而失败的调用并查看响应数据

include_once dirname(__FILE__) . '/vendor/autoload.php';

use Clivern\Monkey\Util\Config;
use Clivern\Monkey\API\Request\PlainRequest;
use Clivern\Monkey\API\Response\PlainResponse;
use Clivern\Monkey\API\Request\RequestMethod;
use Clivern\Monkey\API\Request\RequestType;
use Clivern\Monkey\API\Caller;


// Create a cloudStack credentials config
$config = new Config();
$config->addCloudStackServer("us_dc_clsk_01", [
    "api_url"   => "http://clsk_url.com:8080/client/api",
    "api_key"    => "api_key_here",
    "secret_key" => "secret_key_here"
]);

// Create request object with a missing parameter account :(
$request = new PlainRequest();
$request->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$SYNCHRONOUS)
        ->addParameter("command", "createUser")
        ->addParameter("email", "hello@clivern.com")
        ->addParameter("firstname", "John")
        ->addParameter("lastname", "Doe")
        ->addParameter("password", "clivern")
        ->addParameter("username", "clivern");

// Create response object without callbacks
$response = new PlainResponse();

// Create a caller object with the request and response and ident create_account
$caller = new Caller($request, $response, "create_account", $config->getCloudStackServer("us_dc_clsk_01"));

// Run the call
$caller->execute();

// Debug the caller status and response data
var_dump($caller->getStatus()); // Return string(6) "FAILED"
var_dump($caller->response()->getResponse()); // Returns array(0) { }
var_dump($caller->response()->getErrorCode()); // Returns int(431)
var_dump($caller->response()->getErrorMessage()); // Returns string(73) "Unable to execute API command createuser due to missing parameter account"

现在让我们创建一个成功的调用

include_once dirname(__FILE__) . '/vendor/autoload.php';

use Clivern\Monkey\Util\Config;
use Clivern\Monkey\API\Request\PlainRequest;
use Clivern\Monkey\API\Response\PlainResponse;
use Clivern\Monkey\API\Request\RequestMethod;
use Clivern\Monkey\API\Request\RequestType;
use Clivern\Monkey\API\Caller;


// Create a cloudStack credentials config
$config = new Config();
$config->addCloudStackServer("us_dc_clsk_01", [
    "api_url"   => "http://clsk_url.com:8080/client/api",
    "api_key"    => "api_key_here",
    "secret_key" => "secret_key_here"
]);

// Create request object
$request = new PlainRequest();
$request->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$SYNCHRONOUS)
        ->addParameter("command", "createUser")
        ->addParameter("account", "admin")
        ->addParameter("email", "hello@clivern.com")
        ->addParameter("firstname", "John")
        ->addParameter("lastname", "Doe")
        ->addParameter("password", "clivern")
        ->addParameter("username", "clivern");

// Create response object without callbacks
$response = new PlainResponse();

// Create a caller object with the request and response and ident create_account
$caller = new Caller($request, $response, "create_account", $config->getCloudStackServer("us_dc_clsk_01"));

// Run the call
$caller->execute();

// Debug the caller status and response data
var_dump($caller->getStatus()); // Return string(9) "SUCCEEDED"
var_dump($caller->response()->getResponse()); // Returns array(1) { ["createuserresponse"]=> array(1) { ["user"]=> array(18) { ["id"]=> string(36) "6980f41b-73e5-4848-ad90-7859efb613ad" .....}}}
var_dump($caller->response()->getErrorCode()); // Returns string(0) ""
var_dump($caller->response()->getErrorMessage()); // Returns string(0) ""

运行异步任务

在异步调用的情况下,我们需要使用另一个名为 Job 的类来执行我们的调用者。该 Job 类可以导出为 json 编码的字符串并存储在数据库中,然后从最后的状态重新加载。这意味着我们可以构建一个包含大量同步和异步调用的作业,并且作业类将在我们每次重新加载它时继续,并完成主要请求。

此外,如果调用失败,Job 类会重试运行调用者,一旦成功,它将移动到下一个调用者。当然,您将为每个作业或每个调用者提供尝试次数。

让我们首先创建一个 将虚拟机停止的任务。此作业至少需要运行两次,一次创建机器,另一次检查作业状态。由于我们不使用数据库来存储作业状态,我们将手动执行此操作。但在现实生活中,我们将在数据库中存储作业并在后台运行。

include_once dirname(__FILE__) . '/vendor/autoload.php';

use Clivern\Monkey\Util\Config;
use Clivern\Monkey\API\Request\PlainRequest;
use Clivern\Monkey\API\Response\PlainResponse;
use Clivern\Monkey\API\Request\RequestMethod;
use Clivern\Monkey\API\Request\RequestType;
use Clivern\Monkey\API\Caller;
use Clivern\Monkey\API\Job;
use Clivern\Monkey\API\DumpType;
use Clivern\Monkey\API\Factory;
use Clivern\Monkey\API\JobStatus;


$config = new Config();
$config->addCloudStackServer("us_dc_clsk_01", [
    "api_url"   => "http://clsk_url.com:8080/client/api",
    "api_key"    => "api_key_here",
    "secret_key" => "secret_key_here"
]);

$request = new PlainRequest();
$request->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$ASYNCHRONOUS)
        ->addParameter("command", "stopVirtualMachine")
        ->addParameter("id", "4c9c8759-de26-41bb-9a22-fe51b9f0c9af");

$response = new PlainResponse();

$caller = new Caller($request, $response, "stop_virtual_machine", $config->getCloudStackServer("us_dc_clsk_01"));


// Create a job with one caller and 4 default trials in case of failure
$job = new Job([
    $caller
], 4);

// Job initial state to store in database
$initialJobState = $job->dump(DumpType::$JSON);
var_dump($initialJobState);

$currentJobState = $initialJobState;
$finished = false;
$currentJob = null;

while (!$finished) {
    $currentJob = Factory::job()->reload($currentJobState, DumpType::$JSON);
    $currentJob->execute();
    $finished = (($currentJob->getStatus() == JobStatus::$FAILED) || ($currentJob->getStatus() == JobStatus::$SUCCEEDED)) ? true : false;
    $currentJobState = $currentJob->dump(DumpType::$JSON);
    sleep(5);
}

if( $currentJob != null ){
    var_dump($currentJob->getStatus());
    var_dump($currentJob->getCaller("stop_virtual_machine")->getStatus());
    var_dump($currentJob->getCaller("stop_virtual_machine")->response()->getResponse());
    var_dump($currentJob->getCaller("stop_virtual_machine")->response()->getErrorCode());
    var_dump($currentJob->getCaller("stop_virtual_machine")->response()->getErrorMessage());
    var_dump($currentJob->dump(DumpType::$JSON));
}

此外,我们还可以 再次启动虚拟机

include_once dirname(__FILE__) . '/vendor/autoload.php';

use Clivern\Monkey\Util\Config;
use Clivern\Monkey\API\Request\PlainRequest;
use Clivern\Monkey\API\Response\PlainResponse;
use Clivern\Monkey\API\Request\RequestMethod;
use Clivern\Monkey\API\Request\RequestType;
use Clivern\Monkey\API\Caller;
use Clivern\Monkey\API\Job;
use Clivern\Monkey\API\DumpType;
use Clivern\Monkey\API\Factory;
use Clivern\Monkey\API\JobStatus;


$config = new Config();
$config->addCloudStackServer("us_dc_clsk_01", [
    "api_url"   => "http://clsk_url.com:8080/client/api",
    "api_key"    => "api_key_here",
    "secret_key" => "secret_key_here"
]);

$request = new PlainRequest();
$request->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$ASYNCHRONOUS)
        ->addParameter("command", "startVirtualMachine")
        ->addParameter("id", "4c9c8759-de26-41bb-9a22-fe51b9f0c9af");

$response = new PlainResponse();

$caller = new Caller($request, $response, "start_virtual_machine", $config->getCloudStackServer("us_dc_clsk_01"));


// Create a job with one caller and 4 default trials in case of failure
$job = new Job([
    $caller
], 4);

// Job initial state to store in database
$initialJobState = $job->dump(DumpType::$JSON);
var_dump($initialJobState);

$currentJobState = $initialJobState;
$finished = false;
$currentJob = null;

while (!$finished) {
    $currentJob = Factory::job()->reload($currentJobState, DumpType::$JSON);
    $currentJob->execute();
    $finished = (($currentJob->getStatus() == JobStatus::$FAILED) || ($currentJob->getStatus() == JobStatus::$SUCCEEDED)) ? true : false;
    $currentJobState = $currentJob->dump(DumpType::$JSON);
    sleep(5);
}

if( $currentJob != null ){
    var_dump($currentJob->getStatus());
    var_dump($currentJob->getCaller("start_virtual_machine")->getStatus());
    var_dump($currentJob->getCaller("start_virtual_machine")->response()->getResponse());
    var_dump($currentJob->getCaller("start_virtual_machine")->response()->getErrorCode());
    var_dump($currentJob->getCaller("start_virtual_machine")->response()->getErrorMessage());
    var_dump($currentJob->dump(DumpType::$JSON));
}

运行复杂作业

如果我们想运行两个调用,但它们彼此独立,这完全取决于顺序。我们只需按顺序运行一个,然后运行另一个,例如停止和启动虚拟机。在这种情况下,我们将创建两个调用者,并创建一个包含这两个调用者的作业,如下所示

include_once dirname(__FILE__) . '/vendor/autoload.php';

use Clivern\Monkey\Util\Config;
use Clivern\Monkey\API\Request\PlainRequest;
use Clivern\Monkey\API\Response\PlainResponse;
use Clivern\Monkey\API\Request\RequestMethod;
use Clivern\Monkey\API\Request\RequestType;
use Clivern\Monkey\API\Caller;
use Clivern\Monkey\API\Job;
use Clivern\Monkey\API\DumpType;
use Clivern\Monkey\API\Factory;
use Clivern\Monkey\API\JobStatus;


$config = new Config();
$config->addCloudStackServer("us_dc_clsk_01", [
    "api_url"   => "http://clsk_url.com:8080/client/api",
    "api_key"    => "api_key_here",
    "secret_key" => "secret_key_here"
]);

$request1 = new PlainRequest();
$request1->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$ASYNCHRONOUS)
        ->addParameter("command", "stopVirtualMachine")
        ->addParameter("id", "4c9c8759-de26-41bb-9a22-fe51b9f0c9af");

$response1 = new PlainResponse();

$caller1 = new Caller($request1, $response1, "stop_virtual_machine", $config->getCloudStackServer("us_dc_clsk_01"));


$request2 = new PlainRequest();
$request2->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$ASYNCHRONOUS)
        ->addParameter("command", "startVirtualMachine")
        ->addParameter("id", "4c9c8759-de26-41bb-9a22-fe51b9f0c9af");

$response2 = new PlainResponse();

$caller2 = new Caller($request2, $response2, "start_virtual_machine", $config->getCloudStackServer("us_dc_clsk_01"));


// Create a job with two callers and 4 default trials in case of failure
$job = new Job([
    $caller1,
    $caller2
], 4);

// Job initial state to store in database
$initialJobState = $job->dump(DumpType::$JSON);
var_dump($initialJobState);

$currentJobState = $initialJobState;
$finished = false;
$currentJob = null;

while (!$finished) {
    $currentJob = Factory::job()->reload($currentJobState, DumpType::$JSON);
    $currentJob->execute();
    $finished = (($currentJob->getStatus() == JobStatus::$FAILED) || ($currentJob->getStatus() == JobStatus::$SUCCEEDED)) ? true : false;
    $currentJobState = $currentJob->dump(DumpType::$JSON);
    sleep(5);
}

if( $currentJob != null ){
    var_dump($currentJob->getStatus());
    var_dump($currentJob->getCaller("stop_virtual_machine")->getStatus());
    var_dump($currentJob->getCaller("stop_virtual_machine")->response()->getResponse());
    var_dump($currentJob->getCaller("stop_virtual_machine")->response()->getErrorCode());
    var_dump($currentJob->getCaller("stop_virtual_machine")->response()->getErrorMessage());
    var_dump($currentJob->getCaller("start_virtual_machine")->getStatus());
    var_dump($currentJob->getCaller("start_virtual_machine")->response()->getResponse());
    var_dump($currentJob->getCaller("start_virtual_machine")->response()->getErrorCode());
    var_dump($currentJob->getCaller("start_virtual_machine")->response()->getErrorMessage());
    var_dump($currentJob->dump(DumpType::$JSON));
}

更复杂的用法

让我们让它更复杂,现在我们需要部署一个虚拟服务器,这些数据如下

  • 模板 CentOS 5.6 (64-bit) no GUI (Simulator)
  • 服务提供: 小型实例
  • 区域: Sandbox-simulator

如您所知,从 API 中,我们需要模板、服务提供和区域的 id。在这种情况下,我们将在部署虚拟服务器之前创建一个单独的调用者来获取这些 id。然后我们将使用响应回调将它们存储在调用者共享数据中,供作业对象使用。

include_once dirname(__FILE__) . '/vendor/autoload.php';

use Clivern\Monkey\Util\Config;
use Clivern\Monkey\API\Request\PlainRequest;
use Clivern\Monkey\API\Response\PlainResponse;
use Clivern\Monkey\API\Request\RequestMethod;
use Clivern\Monkey\API\Request\RequestType;
use Clivern\Monkey\API\Caller;
use Clivern\Monkey\API\Job;
use Clivern\Monkey\API\DumpType;
use Clivern\Monkey\API\Factory;
use Clivern\Monkey\API\JobStatus;
use Clivern\Monkey\API\CallerStatus;


class TemplatesFilter
{
    public static function addTemplateId($caller, $arguments)
    {
        if ($caller->getStatus() !=  CallerStatus::$SUCCEEDED) {
            return false;
        }
        $response = $caller->response()->getResponse();
        if( !is_array($response) || !isset($response["listtemplatesresponse"]) || !isset($response["listtemplatesresponse"]["template"]) ){
            return false;
        }
        foreach ($response["listtemplatesresponse"]["template"] as $template) {
            if(isset($arguments['template_name']) && ($template['name'] == $arguments['template_name'])) {
                $caller->addItem("templateid", $template['id']);
                break;
            }elseif(!isset($arguments['template_name'])){
                $caller->addItem("templateid", $template['id']);
                break;
            }
        }

        if( empty($caller->getItem("templateid")) ){
            $caller->setStatus(CallerStatus::$FAILED);
            $caller->response()->setErrorCode("M200");
            $caller->response()->setErrorMessage((isset($arguments['template_name']))
                ? sprintf("Error! Can't find template with name: %s", $arguments['template_name'])
                : "Error! Can't find any template."
            );
        }
    }
}

class ServiceOfferingsFilter
{
    public static function addServiceOfferId($caller, $arguments)
    {
        if ($caller->getStatus() !=  CallerStatus::$SUCCEEDED) {
            return false;
        }
        $response = $caller->response()->getResponse();
        if( !is_array($response) || !isset($response["listserviceofferingsresponse"]) || !isset($response["listserviceofferingsresponse"]["serviceoffering"]) ){
            return false;
        }
        foreach ($response["listserviceofferingsresponse"]["serviceoffering"] as $serviceoffering) {
            if(isset($arguments['serviceoffering_name']) && ($serviceoffering['name'] == $arguments['serviceoffering_name'])) {
                $caller->addItem("serviceofferingid", $serviceoffering['id']);
                break;
            }elseif(!isset($arguments['serviceoffering_name'])){
                $caller->addItem("serviceofferingid", $serviceoffering['id']);
                break;
            }
        }
        if( empty($caller->getItem("serviceofferingid")) ){
            $caller->setStatus(CallerStatus::$FAILED);
            $caller->response()->setErrorCode("M200");
            $caller->response()->setErrorMessage((isset($arguments['serviceoffering_name']))
                ? sprintf("Error! Can't find service offering with name: %s", $arguments['serviceoffering_name'])
                : "Error! Can't find any service offering."
            );
        }
    }
}

class ZoneFilter
{
    public static function addZoneId($caller, $arguments)
    {
        if ($caller->getStatus() !=  CallerStatus::$SUCCEEDED) {
            return false;
        }
        $response = $caller->response()->getResponse();
        if( !is_array($response) || !isset($response["listzonesresponse"]) || !isset($response["listzonesresponse"]["zone"]) ){
            return false;
        }
        foreach ($response["listzonesresponse"]["zone"] as $zone) {
            if(isset($arguments['zone_name']) && ($zone['name'] == $arguments['zone_name'])) {
                $caller->addItem("zoneid", $zone['id']);
                break;
            }elseif(!isset($arguments['zone_name'])){
                $caller->addItem("zoneid", $zone['id']);
                break;
            }
        }
        if( empty($caller->getItem("zoneid")) ){
            $caller->setStatus(CallerStatus::$FAILED);
            $caller->response()->setErrorCode("M200");
            $caller->response()->setErrorMessage((isset($arguments['zone_name']))
                ? sprintf("Error! Can't find zone with name: %s", $arguments['zone_name'])
                : "Error! Can't find any zone."
            );
        }
    }
}

$config = new Config();
$config->addCloudStackServer("us_dc_clsk_01", [
    "api_url"   => "http://clsk_url.com:8080/client/api",
    "api_key"    => "api_key_here",
    "secret_key" => "secret_key_here"
]);

$request1 = new PlainRequest();
$request1->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$SYNCHRONOUS)
        ->addParameter("command", "listTemplates")
        ->addParameter("templatefilter", "featured");

$response1 = new PlainResponse("\TemplatesFilter::addTemplateId", ["template_name" => "CentOS 5.6 (64-bit) no GUI (Simulator)"]);

$caller1 = new Caller($request1, $response1, "list_templates", $config->getCloudStackServer("us_dc_clsk_01"));


$request2 = new PlainRequest();
$request2->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$SYNCHRONOUS)
        ->addParameter("command", "listServiceOfferings");

$response2 = new PlainResponse("\ServiceOfferingsFilter::addServiceOfferId", ["serviceoffering_name" => "Small Instance"]);

$caller2 = new Caller($request2, $response2, "list_service_offering", $config->getCloudStackServer("us_dc_clsk_01"));


$request3 = new PlainRequest();
$request3->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$SYNCHRONOUS)
        ->addParameter("command", "listZones");

$response3 = new PlainResponse("\ZoneFilter::addZoneId", ["zone_name" => "Sandbox-simulator"]);

$caller3 = new Caller($request3, $response3, "list_zone", $config->getCloudStackServer("us_dc_clsk_01"));


$request4 = new PlainRequest();
$request4->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$ASYNCHRONOUS)
        ->addParameter("command", "deployVirtualMachine")
        ->addParameter("serviceofferingid", "@list_service_offering->serviceofferingid")
        ->addParameter("templateid", "@list_templates->templateid")
        ->addParameter("zoneid", "@list_zone->zoneid");

$response4 = new PlainResponse();

$caller4 = new Caller($request4, $response4, "deploy_virtual_machine", $config->getCloudStackServer("us_dc_clsk_01"));


// Create a job with four callers and 4 default trials in case of failure
$job = new Job([
    $caller1,
    $caller2,
    $caller3,
    $caller4
], 4);

// Job initial state to store in database
$initialJobState = $job->dump(DumpType::$JSON);
var_dump($initialJobState);

$currentJobState = $initialJobState;
$finished = false;
$currentJob = null;

while (!$finished) {
    $currentJob = Factory::job()->reload($currentJobState, DumpType::$JSON);
    $currentJob->execute();
    $finished = (($currentJob->getStatus() == JobStatus::$FAILED) || ($currentJob->getStatus() == JobStatus::$SUCCEEDED)) ? true : false;
    $currentJobState = $currentJob->dump(DumpType::$JSON);
    sleep(5);
}

if( $currentJob != null ){
    var_dump($currentJob->getStatus());

    var_dump($currentJob->getCaller("list_service_offering")->getStatus());
    var_dump($currentJob->getCaller("list_service_offering")->response()->getResponse());
    var_dump($currentJob->getCaller("list_service_offering")->response()->getErrorCode());
    var_dump($currentJob->getCaller("list_service_offering")->response()->getErrorMessage());

    var_dump($currentJob->getCaller("list_templates")->getStatus());
    var_dump($currentJob->getCaller("list_templates")->response()->getResponse());
    var_dump($currentJob->getCaller("list_templates")->response()->getErrorCode());
    var_dump($currentJob->getCaller("list_templates")->response()->getErrorMessage());

    var_dump($currentJob->getCaller("list_zone")->getStatus());
    var_dump($currentJob->getCaller("list_zone")->response()->getResponse());
    var_dump($currentJob->getCaller("list_zone")->response()->getErrorCode());
    var_dump($currentJob->getCaller("list_zone")->response()->getErrorMessage());

    var_dump($currentJob->getCaller("deploy_virtual_machine")->getStatus());
    var_dump($currentJob->getCaller("deploy_virtual_machine")->response()->getResponse());
    var_dump($currentJob->getCaller("deploy_virtual_machine")->response()->getErrorCode());
    var_dump($currentJob->getCaller("deploy_virtual_machine")->response()->getErrorMessage());
    var_dump($currentJob->dump(DumpType::$JSON));
}

Monkey 在生产中

在这里,我试图描述 monkey 的不同用法,但在生产中,我们必须为我们的作业和执行器拥有数据库表,以便在后台运行作业。

我们需要为每个特定命令创建自定义请求类,这样我们就不需要在创建请求时提供命令数据。

use Clivern\Monkey\API\Contract\RequestInterface;
use Clivern\Monkey\API\Request\PlainRequest;


class CreateUser extends PlainRequest implements RequestInterface {

}

我们需要为每个特定命令创建自定义响应类,这样我们就不需要解析响应来提取有用的响应数据,并有一个直接的方法来做这件事。

use Clivern\Monkey\API\Contract\ResponseInterface;
use Clivern\Monkey\API\Response\PlainResponse;


class CreateUser extends PlainResponse implements ResponseInterface {

}

同时构建我们的响应回调函数,以便在调用时,我们确保这些数据在作业中对其他调用者可用。

作为命令行工具的使用

创建一个可执行文件 run

$ touch run
$ chmod u+x run
#!/usr/bin/env php
<?php

include_once dirname(__FILE__) . '/vendor/autoload.php';

use Clivern\Monkey\Util\Config;
use Clivern\Monkey\API\Request\PlainRequest;
use Clivern\Monkey\API\Response\PlainResponse;
use Clivern\Monkey\API\Request\RequestMethod;
use Clivern\Monkey\API\Request\RequestType;
use Clivern\Monkey\API\Caller;

$platform = false;

foreach ($argv as $value) {
    if(strpos($value, "platform=") !== false){
        $platform = str_replace("platform=", "", $value);
    }
}

$command = false;

foreach ($argv as $value) {
    if(strpos($value, "command=") !== false){
        $command = str_replace("command=", "", $value);
    }
}

if(empty($command) || empty($platform)){
    die("Please Provide Command and The Platform ID");
}

$config = new Config();
$config->addCloudStackServer("us_dc_clsk_01", [
    "api_url"   => "http://clsk_url.com:8080/client/api",
    "api_key"    => "api_key_here",
    "secret_key" => "secret_key_here"
]);


$request = new PlainRequest();
$request->setMethod(RequestMethod::$GET)
        ->setType(RequestType::$SYNCHRONOUS)
        ->addParameter("command", $command);


foreach ($argv as $value) {
    if((strpos($value, "command=") === false) && (strpos($value, "platform=") === false) && strpos($value, "=")){
        $parameter = explode("=", $value);
        $request->addParameter($parameter[0], $parameter[1]);
    }
}

// Create response object without callbacks
$response = new PlainResponse();

// Create a caller object with the request and response and ident
$caller = new Caller($request, $response, $command, $config->getCloudStackServer($platform));

// Run the call
$caller->execute();

$data = $caller->response()->getResponse();

echo json_encode($data);
$ ./run platform=us_dc_clsk_01 command=$$ arg=$$
$ ./run platform=us_dc_clsk_01 command=$$ arg=$$ | python -m json.tool

杂项

变更日志

版本 1.1.0

Update dependencies.

版本 1.0.6

Enhance code style.
Automate code fixes and linting.

版本 1.0.5

Docs Updated.

版本 1.0.4

Docs Updated.

版本 1.0.3

Docs Updated.

版本 1.0.2

Force caller failure in callbacks in case of unexpected response.

版本 1.0.1

Add More Test Cases.

版本 1.0.0

Initial Release.

致谢

© 2018, Clivern. 在 MIT 许可证 下发布。

Monkey@clivern 撰写和维护。