Passed
Push — develop ( ef97e9...11ccd2 )
by Nikolay
04:33
created

YandexCloud::provision()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 33
rs 9.584
cc 3
nc 2
nop 0
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright © 2017-2024 Alexey Portnov and Nikolay Beketov
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with this program.
17
 * If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
namespace MikoPBX\Core\System\CloudProvisioning;
21
22
use MikoPBX\Core\System\Util;
23
24
class YandexCloud extends CloudProvider
25
{
26
    const CLOUD_NAME='YandexCloud';
27
28
    /**
29
     * Performs the Yandex Cloud provisioning.
30
     *
31
     * @return bool True if the provisioning was successful, false otherwise.
32
     */
33
    public function provision(): bool
34
    {
35
        Util::sysLogMsg(__CLASS__, 'Try '.self::CLOUD_NAME.' provisioning... ');
36
37
        $curl = curl_init();
38
        $url = 'http://169.254.169.254/computeMetadata/v1/instance/?recursive=true';
39
        curl_setopt($curl, CURLOPT_URL, $url);
40
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
41
        curl_setopt($curl, CURLOPT_TIMEOUT, self::HTTP_TIMEOUT);
42
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['Metadata-Flavor:Google']);
43
        $resultRequest = curl_exec($curl);
44
45
        $http_code = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
46
        curl_close($curl);
47
        if ($http_code !== 200 || !is_string($resultRequest)) {
48
            return false;
49
        }
50
        $data = json_decode($resultRequest, true);
51
52
        // Update SSH keys, if available
53
        $this->updateSSHKeys($data['attributes']['ssh-keys'] ?? '');
54
55
        // Update LAN settings with hostname and external IP address
56
        $hostname = $data['name'] ?? '';
57
        $extIp = $data['networkInterfaces'][0]['accessConfigs'][0]['externalIp'] ?? '';
58
        $this->updateLanSettings($hostname, $extIp);
59
60
        // Update SSH and WEB passwords using some unique identifier from the metadata
61
        $vmId = $data['id'] ?? '';
62
        $this->updateSSHPassword($vmId);
63
        $this->updateWebPassword($vmId);
64
65
        return true;
66
    }
67
}