自从买了198三年的腾讯轻量云真香机,就迫不及待的把之前CVM上的数据都迁过来了,轻量云除了带宽增加,同时对应的缺点是流量有限制(1000G对我们这种打单机的网站来说简直是绰绰有余)。另一个缺点是CVM可以直接控制台弄云硬盘的定时快照策略,轻量云是只能手动在控制台建立快照和删除快照的,并不提供控制台的快照策略,好在它是提供了服务端api的,于是咱们就自己动手来弄这个定时建立快照的功能。

需要注意的是,免费的快照有限制,一台机器只能提供两个免费的实例,那么实现的逻辑就好说了:新增加一个定时任务,每次都删除最早建立的快照,同时创建一个新的快照。

轻量云调用的快照api与云硬盘文档部分的api是不一样的,这个需要注意。

轻量云快照服务端api相关的文档:

腾讯云做得比较好的是直接做好了api调试工具,可以生成代码,如PHP、Java、Python、Node.js、go等, 腾讯云api在线调试

图省事的话直接用生成的代码自己再加一点错误捕获的逻辑就可以了。

我这边用的是世界上最好的语言,先安装对应的sdk。

腾讯云SDK地址:

流程:

  • 全量安装sdk或者只安装自己需要的,全量安装使用composer require tencentcloud/tencentcloud-sdk-php,而按需安装则是使用composer require tencentcloud/产品名,比如我们这次要用到是是轻量服务器,则是composer require tencentcloud/lighthouse
  • 安装好后把从api调试控制台生成的代码拷备进来,关键代码如下面所示。
  • 加入到定时任务到crontab。

附上关键代码:

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Lighthouse\V20200324\LighthouseClient;
use TencentCloud\Lighthouse\V20200324\Models\DescribeSnapshotsRequest;
use TencentCloud\Lighthouse\V20200324\Models\DeleteSnapshotsRequest;
use TencentCloud\Lighthouse\V20200324\Models\CreateInstanceSnapshotRequest;

protected function execute(Input $input, Output $output)
{
    $output->writeln(date("Y-m-d H:i:s") . "===开始备份硬盘快照");
    try {
        $cred = new Credential(config('qcloud.SecretId'), config("qcloud.SecretKey"));
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("lighthouse.tencentcloudapi.com");

        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new LighthouseClient($cred, "ap-chengdu", $clientProfile);

        $req = new DescribeSnapshotsRequest();

        $params = array(

        );
        $req->fromJsonString(json_encode($params));

        $resp = $client->DescribeSnapshots($req);
        //只有两个快照的情况下才进行删除,防止数据出错没有回滚的快照
        if(isset($resp->TotalCount) && $resp->TotalCount > 1)
        {
            //删除第一个快照
            $delTarget = Arr::last($resp->SnapshotSet);
            $req = new DeleteSnapshotsRequest();

            $params = array(
                "SnapshotIds" => array( $delTarget->SnapshotId )
            );
            $req->fromJsonString(json_encode($params));

            $resp = $client->DeleteSnapshots($req);
            $output->writeln($resp->toJsonString());
            $req = new CreateInstanceSnapshotRequest();

            $params = array(
                "InstanceId" => config("qcloud.lighthouse_instance_id")
            );
            $req->fromJsonString(json_encode($params));

            $resp = $client->CreateInstanceSnapshot($req);

           $output->writeln($resp->toJsonString());
            $output->writeln(date("Y-m-d H:i:s") . "===备份硬盘快照结束");

        }
    } catch (Exception $e) {
        //用bark进行错误通知
        bark($e->getMessage());
    }

}

标签: none

评论已关闭