public function setImage($platform, $cloudLocation, $imageId, $userId, $userEmail)
{
if (in_array($platform, [\SERVER_PLATFORMS::GCE, \SERVER_PLATFORMS::AZURE])) {
$cloudLocation = '';
}
$history = new ImageHistory();
$history->roleId = $this->id;
$history->platform = $platform;
$history->cloudLocation = $cloudLocation;
$history->addedById = $userId;
$history->addedByEmail = $userEmail;
$oldImage = null;
try {
$oldImage = $this->getImage($platform, $cloudLocation);
$history->oldImageId = $oldImage->imageId;
if ($imageId) {
if ($oldImage->imageId == $imageId) {
return;
}
}
} catch (\Exception $e) {
}
if ($imageId) {
/* @var $newImage Image */
$newImage = Image::findOne([['id' => $imageId], ['platform' => $platform], ['cloudLocation' => $cloudLocation], ['$or' => [['accountId' => null], ['$and' => [['accountId' => $this->accountId], ['$or' => [['envId' => null], ['envId' => $this->envId]]]]]]]]);
if (!$newImage) {
throw new ImageNotFoundException(sprintf("The Image does not exist, or isn't owned by your account: %s, %s, %s", $platform, $cloudLocation, $imageId));
}
if ($newImage->status !== Image::STATUS_ACTIVE) {
throw new NotAcceptableImageStatusException(sprintf("You can't add image %s because of its status: %s", $newImage->id, $newImage->status));
}
if ($newImage->getOs()->family && $newImage->getOs()->generation) {
// check only if they are set
if ($this->getOs()->family != $newImage->getOs()->family || $this->getOs()->generation != $newImage->getOs()->generation) {
throw new OsMismatchException(sprintf("OS mismatch between Image: %s, family: %s and Role: %d, family: %s", $newImage->id, $newImage->getOs()->family, $this->id, $this->getOs()->family));
}
}
if ($this->isScalarized && !($newImage->isScalarized || $newImage->hasCloudInit)) {
throw new ImageNotScalarizedException("You can not add the Image {$newImage->id} because neither it is not use Scalr Agent nor cloud-init");
}
$history->imageId = $newImage->id;
if ($oldImage) {
$oldImage->delete();
}
$newRoleImage = new RoleImage();
$newRoleImage->roleId = $this->id;
$newRoleImage->imageId = $newImage->id;
$newRoleImage->platform = $newImage->platform;
$newRoleImage->cloudLocation = $newImage->cloudLocation;
$newRoleImage->save();
} else {
if ($oldImage) {
if ($oldImage->isUsed()) {
throw new ImageInUseException(sprintf("The Image for roleId: %d, platform: %s, cloudLocation: %s is used by some FarmRole", $oldImage->roleId, $oldImage->platform, $oldImage->cloudLocation));
}
$oldImage->delete();
}
}
$history->save();
}