php Azure NodeJS Function + Azure App Service与Get Request的问题

8yoxcaq7  于 6个月前  发布在  PHP
关注(0)|答案(1)|浏览(72)

我有一个Azure函数在计时器触发器上运行。

const { app } = require('@azure/functions');

app.timer('Cron', {
    schedule: '0 0 */1 * * *',
    handler: async (timer, context) => { // 2
        const url = 'https://xxx/backup/index.php';
        const headers = {
            'key': 'key'
        };
    
        await fetch(url, { headers })
        .then(resp => resp.text())
        .then(data => { context.log(data); })
        .catch(err => { context.log(err); });
    }
});

字符串
这将对位于执行备份的App Services上的PHP文件执行get请求。
如果我通过Web浏览器https://xxx/backup/index.php手动点击URL,备份文件将被创建。
但是,当Azure函数运行时,不会生成备份文件。我可以在nginx访问日志中看到来自Azure函数的请求,HTTP代码为200。
PHP文件只是在请求时创建一个mysql转储。还没有认证(所以忽略nodejs代码中的自定义头)。
我错过了什么吗?
我尝试通过Azure Portal在Functions Code/Test编辑器中手动运行代码,但结果仍然相同。成功请求应用服务,但未生成备份文件。
这是我通过浏览器手动点击URL时的nginx日志

xxx.xxx.xxx.xxx - - [03/Dec/2023:09:12:41 +0000] "GET /backup/ HTTP/1.1" 200 100 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"


这是azure函数运行时的日志

xxx.xxx.xxx.xxx - - [03/Dec/2023:07:17:00 +0000] "GET /backup/index.php HTTP/1.1" 200 31 "-" "undici"


这是在AppService上运行的php备份脚本

<?php
require 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__, '../../.env');
$dotenv->load();

$host                 = $_ENV['DB_HOST'];
$username             = $_ENV['DB_USERNAME'];
$password             = $_ENV['DB_PASSWORD'];
$database             = $_ENV['DB_DATABASE'];
$encryption_key       = $_ENV['ENCRYPTION_KEY'];
$ssl_cert             = $_ENV['MYSQL_ATTR_SSL_CA'];

$encFile = './backup-'.date('d-m-Y') .'.sql.gz.enc';

// MySQL dump command, gzip, and encrypt in a single pipeline
$command = sprintf(
  'mysqldump --no-tablespaces --ssl=1 --ssl-ca=%s -h %s -u %s -p%s %s | gzip -9 | openssl enc -aes-256-cbc -salt -k %s > %s',
  $ssl_cert,
  $host,
  $username,
  $password,
  $database,
  $encryption_key,
  $encFile
);

// Execute the pipeline
exec($command, $output, $exitCode);

if ($exitCode !== 0) die("Backup failed with exit code $exitCode\n");

echo "Backup completed successfully. Filename: $encFile\n";
?>

uurity8g

uurity8g1#

  • 我对你的代码做了一些修改,可以从PHP和定时器触发器函数代码生成备份文件。*
    产品代码:
  • backup-index.php:*
<?php

require __DIR__ . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$result = generateBackup();

if ($result) {
    echo "Backup triggered successfully";
} else {
    echo "Failed to trigger backup";
}

function generateBackup() {
    try {
        $host           = $_ENV['DB_HOST'];
        $username       = $_ENV['DB_USERNAME'];
        $password       = $_ENV['DB_PASSWORD'];
        $database       = $_ENV['DB_DATABASE'];
        $encryptionKey  = $_ENV['ENCRYPTION_KEY'];
        $sslCert        = $_ENV['MYSQL_ATTR_SSL_CA'];

        $backupFileName = 'backup-' . date('d-m-Y') . '.sql.gz.enc';
        $backupFilePath = '<path/to/backup_file>' . $backupFileName;

        $mysqldumpPath = 'C:/Program Files/MySQL/MySQL Server 8.0/bin/mysqldump'; 
        $zipPath = 'C:/Program Files/7-Zip/7z.exe';

        $command = sprintf(
            '"%s" --no-tablespaces --ssl=1 --ssl-ca=%s -h %s -u %s -p%s %s | "%s" a -si -tgzip -mx=9 -an | openssl enc -aes-256-cbc -salt -k %s > %s',
            $mysqldumpPath,
            $sslCert,
            $host,
            $username,
            $password,
            $database,
            $zipPath,
            $encryptionKey,
            $backupFilePath
        );

        exec($command, $output, $exitCode);

        error_log(implode("\n", $output)); 

        return $exitCode === 0;
    } catch (Exception $e) {
        error_log('Exception: ' . $e->getMessage());
        return false;
    }
}
?>

字符串

  • .env:*
DB_HOST="<server_name>.mysql.database.azure.com"
DB_USERNAME="<user_name>"
DB_PASSWORD="<password>"
DB_DATABASE="<db_name>"
ENCRYPTION_KEY="<key>"
MYSQL_ATTR_SSL_CA="path/to//DigiCertGlobalRootCA.crt.pem"

  • timerTrigger.js:*
const { app } = require('@azure/functions');

app.timer('Cron', {
    schedule: '0 */5 * * * *', 
    handler: async (timer, context) => {
        const url = 'http://xxxxxxx/backup-index.php'; 
        const headers = {
            'key': 'key'
        };
        try {
            const fetch = await import('node-fetch');
            
            const response = await fetch.default(url, { headers });
            const data = await response.text();

            context.log('Backup triggered successfully. Response:', data);
        } catch (error) {
            context.log('Failed to trigger backup. Error:', error.message);
        }
    }
});

输出:

PHP代码成功运行如下,
x1c 0d1x的数据
它生成了一个备份文件如下。



定时器触发函数成功触发并生成备份文件。


相关问题