【发布时间】:2019-11-17 14:49:41
【问题描述】:
我有一些方法可以检查命令的响应,并根据该响应执行其他操作,或者失败。
我已经把它带到了它检查命令输出并返回 false 的地方,然后继续执行其余的代码。
这里有一些代码
public function upgradeImages($images)
{
$this->pull($images);
echo "Do next method - Fake destroy\n";
echo "Do next method - Fake re-build\n";
}
public function pull($images)
{
// Count how many containers will be attempted to be updated
$countImages = count($images);
echo("Updrading $countImages containers...");
foreach ($images as $key => $image) {
$key = $key + 1;
// Is there a new version of the image?
if ($this->isNewVersion($image)) {
echo("($key/$countImages) Upgrading '$image'");
$this->docker('pull ' . $image);
}
echo("'$image' is at the latest version");
}
}
public function isNewVersion($image)
{
$cmdOutput = (new Process($this->docker('pull ' . $image)));
$cmdOutput->start();
$cmdOutput->wait(function ($type, $buffer) {
if (contains($buffer, 'Image is up to date')) {
return false;
}
return true;
});
}
这里发生的情况是,upgradeImage 运行 pull 方法,pull 方法正在检查 Docker 映像数组并循环查看映像是否有新版本。这是通过运行isNewVersion() 方法来完成的,该方法检查$buffer 的输出并进行比较。
如果isNewVersion() 返回true,它将循环并更新图像。
如果 isNewVersion() 返回 false,它会通过一条消息告诉您它是最新的。
如果该方法返回 false,我希望循环在 ALL 检查发生后退出,而不是在 $this->pull() 之后继续运行 upgradeImages 方法中的代码。如果我在检查后添加exit,它将在第一次检查后退出,而不检查循环的其余部分。
假设我选择了 2 个图像进行更新,并且两者都 不需要 需要更新,输出将是这样的:
Updrading 2 containers...
'composer:latest' is at the latest version
'php:7.2-fpm-alpine' is at the latest version
Fake destroy
Fake re-build
【问题讨论】:
-
您能提供一个示例输出吗?
-
更新了一些输出的帖子
-
我明白了,在这种情况下,期望的行为是不运行破坏并重新构建吗?
-
正确,如果没有要更新的图像,则不需要运行destroy/re-build方法
-
您是否考虑过使用 ansible 而不是 PHP 来编写您的逻辑?它可以让你的生活更轻松,你会或多或少地免费获得幂等性。例如通过 ansible 拉取图像可以使用此处描述的 docker_image 模块存档:docs.ansible.com/ansible/latest/modules/…
标签: php loops docker symfony foreach