openstack php sdk php-opencloud 使用说明

   openstack提供的是rest风格的api接口,其说明文档见:

http://developer.openstack.org/api-ref-guides/bk-api-ref.pdf,为便于理解和简化调用,这里使用开源的php sdk——php-opencoud

目录结构

    vendor

 ---------composer

 ---------guzzle

 ---------psr

 ---------rackspace

               --------------php-opencloud

               ---------------------docs

               ---------------------lib

                                               ---OpenCloud

               ---------------------samples

               ---------------------tests

    composer:提供自动加载的功能

    guzzle:处理http请求

    psr:提供日志功能

    rackspace/php-opencloud/lib/OpenCloudphp封装库

    OpenCloud不仅支持openstackapi,还支持Rackspaceapi

2 UML模型图

     技术分享

  由图中看到,可以从OpenStack客户端中根据需要获取不同的服务对象。计算服务用来管理云主机,通过主机类型、镜像、密钥对和网络等数据就可以创建一台云主机,而且能够对云主机做出暂停、恢复、停止、开始和重启等多种操作,还可以得到基于web vnc的控制台链接。对象存储服务是以容器的形式来存放数据对象,可以给对象名称设置路径前缀来对对象进行分类,组织成类似windows文件夹的结构。

示例代码

3.1 计算服务

<?php
require dirname(__DIR__) . ‘/vendor/autoload.php‘;
use OpenCloud\Openstack;
use OpenCloud\Compute\Constants\ServerState;
use Guzzle\Http\Exception\BadResponseException;
 
error_reporting(0);
 
$client = new Openstack(‘http://192.168.128.0:5000/v2.0‘, array(
    ‘username‘ => ‘admin‘,
    ‘password‘   => ‘ADMIN_PASS‘,
    ‘tenantName‘ => ‘admin‘
));
 
$computeService = $client->computeService(‘nova‘,‘regionOne‘);
 
//1.枚举镜像
$images = $computeService->imageList();
printf("Images-------------------------------------------------------------------------\n");
foreach($images as $image)
{
    printf("ID:%s,Name:%s\n",$image->id,$image->name);
}
 
//2.枚举主机类型
$flavors = $computeService->flavorList();
printf("Flavors-------------------------------------------------------------------------\n");
foreach($flavors as $flavor)
{
    printf("ID:%-36s,Name:%-36s,Vcpus:%d,Ram:%d\n",$flavor->id,$flavor->name,$flavor->vcpus,$flavor->ram);
}
 
//3.枚举密钥对(for windows:加密密码传输 for linux:ssh登录)
$keypairs = $computeService->listKeypairs();
printf("Keypairs------------------------------------------------------------------------\n");
foreach($keypairs as $keypair)
{
    printf("Name:%s\n",$keypair->getName());
}
 
//4.创建云主机
$server = $computeService->server();
 
printf("Create Server-------------------------------------------------------------------\n");
$serverName = ‘test123‘;
$imageId = ‘c36b0707-38ec-45e5-9d62-7e8798f1724f‘;
$flavorId = ‘53b1355a-c7c6-41a6-884f-7b1604002897‘;
$keypairName = ‘testKey‘;
try
{
    $response = $server->create(array(
        ‘name‘ => $serverName,
        ‘imageId‘ => $imageId,
        ‘flavorId‘ => $flavorId,
        ‘keypair‘ => $keypairName,
        ‘metadata‘ => array(
            ‘admin_pass‘ => ‘123456‘,//设置密码
            ‘appid‘ => ‘123456789‘ //设置自定义元数据
        )));
}catch(BadResponseException $e)
{
    echo $e->getResponse();
}
 
printf("ID:%s,Name:%s,Status:%s\n",$server->id,$server->name,$server->status);
 
function GetServerState($server)
{
    printf("Status:%s\n",$server->status);
}
 
//wait for
$server->waitFor(ServerState::ACTIVE,null,GetServerState,1);
 
if (is_object($server->addresses))
{
    foreach ($server->addresses as $netkey => $netvalue)
    {
        printf("\tNetwork name:%s\n",$netkey);
        if (is_array($netvalue))
        {
            foreach ($netvalue as $infokey => $infovalue)
            {
                printf("\t\tIndex:%s\n",$infokey);
                printf("\t\t\tMac:    %s\n",$infovalue->{‘OS-EXT-IPS-MAC:mac_addr‘});
                printf("\t\t\tVersion:%s\n",$infovalue->version);
                printf("\t\t\tAddr:   %s\n",$infovalue->addr);
                printf("\t\t\tType:   %s\n",$infovalue->{‘OS-EXT-IPS:type‘});
            }
        }
    }
}
 
//5.获取vnc访问地址
printf("VNC-----------------------------------------------------------------------------\n");
$console = $server->console();
printf("Type:%s,URL:%s\n",$console->type,$console->url);
 
//6.停止云主机
printf("Stop Server---------------------------------------------------------------------\n");
$server->stop();
 
$server->waitFor(‘SHUTOFF‘,null,GetServerState,1);
 
//7.启动云主机
printf("Start Server--------------------------------------------------------------------\n");
$server->start();
$server->waitFor(ServerState::ACTIVE,null,GetServerState,1);
 
//8.重启云主机
printf("ReBoot Server-------------------------------------------------------------------\n");
//$server->reboot(ServerState::REBOOT_STATE_SOFT);//REBOOT_STATE_SOFT:软重启 REBOOT_STATE_HARD:硬重启
//$server->waitFor(ServerState::ACTIVE,null,GetServerState,1);
 
//9.删除云主机
printf("Delete Server-------------------------------------------------------------------\n");
$server->delete();
 
//10.获取镜像信息
printf("Image Info----------------------------------------------------------------------\n");
$image = $computeService->image($server->image->id);
printf("ID:%s,Name:%s\n",$image->id,$image->name);
 
//11.获取主机类型信息
printf("Flavor Info---------------------------------------------------------------------\n");
$flavor = $computeService->flavor($server->flavor->id);
printf("ID:%s,Name:%s,Vcpus:%d,Ram:%d\n",$flavor->id,$flavor->name,$flavor->vcpus,$flavor->ram);

3.2 对象存储服务

<?php
require dirname(__DIR__) . ‘/vendor/autoload.php‘;
use OpenCloud\Openstack;
use OpenCloud\Common\Constants\Size;
use OpenCloud\ObjectStore\Resource\DataObject;
 
$client = new Openstack(‘http://192.168.128.0:5000/v2.0‘, array(
    ‘username‘ => ‘admin‘,
    ‘password‘   => ‘ADMIN_PASS‘,
    ‘tenantName‘ => ‘admin‘
));
 
//获取对象存储服务
$objectStoreService = $client->objectStoreService(‘swift‘, ‘regionOne‘);
 
//1.创建容器(每个云盘使用者都有一个容器跟其对应)
$containerName = ‘testContainer‘;
printf("Create Container %s------------------------------------------------------\n",$containerName);
//检查名字合法性
$objectStoreService->checkContainerName($containerName);
$container = $objectStoreService->createContainer($containerName);
if($container == false)
{
    $container = $objectStoreService->getContainer($containerName);
}
else
{
    //设置配额
    $container->setBytesQuota(5 * Size::GB); // 5GB
}
 
//2.枚举容器
$containers = $objectStoreService->listContainers();
printf("Containers--------------------------------------------------------------------------\n");
foreach ($containers as $container)
{
    $container = $objectStoreService->getContainer($container->name);
    printf("Name:%-60s,BytesUsed:%15.6fM,ObjectCount:%d",$container->name,$container->getBytesUsed() / 1024 / 1024,$container->getObjectCount());
    $bytesQuota = $container->getBytesQuota();
    if($bytesQuota)
        printf(",BytesQuota:%.6fM",$bytesQuota / 1024 / 1024);
 
    printf("\n");
}
 
//3.容器添加对象
$container = $objectStoreService->getContainer($containerName);
//添加文件
$customHeaders = array(‘Content-Type‘ => ‘text/plain‘);
$fileData = fopen(‘D:/upload_small_object.txt‘, ‘r‘);
$object = $container->uploadObject(‘upload_small_object.txt‘, $fileData,$customHeaders);
//添加目录(注意后面的斜杠)
$dirName = ‘dir1/‘;
$object = $container->uploadObject($dirName,‘‘);
//目录添加文件(文件放到目录中,必须在文件名前加上目录,形成类似a/b/c/d/1.txt结构(目录a/,目录a/b/,目录a/b/c/,目录a/b/c/d/))
$fileData = fopen(‘D:/upload_small_object.txt‘, ‘r‘);
$object = $container->uploadObject($dirName . ‘upload_small_object.txt‘, $fileData,$customHeaders);
//目录下再添加目录
$dirName = $dirName . ‘dir1-1/‘;
$object = $container->uploadObject($dirName,‘‘);
//二级目录下再添加文件
$fileData = fopen(‘D:/upload_small_object.txt‘, ‘r‘);
$object = $container->uploadObject($dirName . ‘upload_small_object.txt‘, $fileData,$customHeaders);
 
//4.枚举对象
printf("%s Objects-----------------------------------------------------------\n",$containerName);
//是目录的最后一个字符是斜杠
$objects = $container->objectList();
foreach ($objects as $object)
{
    printf("Name:%-60s,Size:%15.6fM,LastModified:%s\n",$object->getName(),$object->getContentLength(),$object->getLastModified());
}
 
//5.枚举目录下的对象(设定前缀)
printf("%s Objects---------------------------------------------------------------\n",$dirName);
$objects = $container->objectList(array(‘prefix‘ => $dirName));
foreach ($objects as $object)
{
    printf("Name:%-60s,Size:%15.6fM,LastModified:%s\n",$object->getName(),$object->getContentLength(),$object->getLastModified());
}
 
//6.下载文件
$object = $container->getObject($dirName . ‘upload_small_object.txt‘);
$objectContent = $object->getContent();
$objectContent->rewind();
$stream = $objectContent->getStream();
file_put_contents(‘D:/123.txt‘, $stream);
 
//7.删除容器(删除云盘使用者时删除对应云盘)
$objects = $container->objectList();
//循环删除每个对象(不支持批删)
foreach ($objects as $object)
{
   $object->delete();
}
$container->delete();


本文出自 “破万卷书” 博客,请务必保留此出处http://powanjuanshu.blog.51cto.com/9779836/1624568

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。