Skip to content

Instantly share code, notes, and snippets.

@isra00
Created October 28, 2012 23:36
Show Gist options
  • Save isra00/3970459 to your computer and use it in GitHub Desktop.
Save isra00/3970459 to your computer and use it in GitHub Desktop.
Atomic update from git
<?php
//BEGIN CONFIG
$link_name = 'active_public_html';
$instance1 = 'public_html1';
$instance2 = 'public_html2';
define('LOG_NAME', 'drupaleitor');
define('DATADOG_APIKEY', '');
define('DATADOG_APPKEY', '');
$syslog_facility = LOG_LOCAL0; //One of http://php.net/manual/function.openlog.php
//END CONFIG
function exit_routine_before_start($message='') {
exit_routine('Deploy failed before starting. Rollback not needed. Details: ' . $message . "\n");
}
function logger($entry, $level) {
echo "$entry\n";
syslog($level, $entry);
}
function cmd_fail($cmd, $cmd_output, $log_datadog=false) {
$log_msg = "Command failed: $cmd ";
logger($log_msg . ' · Output: ' . join(' · ', $cmd_output), LOG_ERR);
if ($log_datadog) {
echo "\n*enviando a datadog*\n";
DataDogStatsD::event($log_msg, array('alert_type'=>'error', 'text'=>join("\n", $cmd_output), 'tags'=>array('deploy')));
}
}
function exec_cmd($cmd, $log_datadog_on_error=false) {
$output = '';
$status = null;
exec("$cmd 2>&1", $output, $status);
if (0 == $status) {
logger($cmd, LOG_DEBUG);
return true;
} else {
cmd_fail($cmd, $output, $log_datadog_on_error);
return false;
}
}
function exit_routine($message='') {
closelog();
die($message);
}
//Bootstrap
openlog(LOG_NAME, LOG_ODELAY, $syslog_facility);
if (!file_exists($link_name)) exit_routine_before_start("Link $link_name does not exist.");
if (!file_exists($instance1)) exit_routine_before_start("Instance 1 $instance1 does not exist.");
if (!file_exists($instance2)) exit_routine_before_start("Instance 2 $instance2 does not exist.");
require 'datadogstatsd.php';
DataDogStatsD::configure(DATADOG_APIKEY, DATADOG_APPKEY);
/** @todo Check for w permissions, etc */
//Here we go!
//Get the next deployment dir
$active_current = readlink($link_name);
$active_next = ($active_current == $instance1) ? $instance2 : $instance1;
$pull = exec_cmd("cd $active_next && git pull", true);
if ($pull) {
$cmd_reassign_link = "rm $link_name && ln -s $active_next $link_name";
if (exec($cmd_reassign_link)) {
DataDogStatsD::event("Deploy successful on $active_next", array('alert_type'=>'success', 'tags'=>array('deploy')));
exit_routine('Deploy succesful on ' . $active_next);
}
} else {
logger("Deploy FAILED", LOG_CRIT);
DataDogStatsD::event("Deploy failed on $active_next. See logs.", array('alert_type'=>'error', 'tags'=>array('deploy')));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment