SAAS-582 - Added provisioning class to create database from within Airtime

This commit is contained in:
Duncan Sommerville 2015-02-12 15:39:22 -05:00
parent dd095e8933
commit ad5536dedd
3 changed files with 138 additions and 76 deletions

View file

@ -7,11 +7,6 @@ use Aws\S3\S3Client;
class ProvisioningController extends Zend_Controller_Action
{
static $dbh;
// Parameter values
private $dbuser, $dbpass, $dbname, $dbhost;
public function init()
{
}
@ -39,76 +34,5 @@ class ProvisioningController extends Zend_Controller_Action
->setHttpResponseCode(200)
->appendBody("OK");
}
/**
* RESTful endpoint for setting up and installing the Airtime database
*/
public function createDatabaseAction() {
Logging::info("Create Database action received");
if (!RestAuth::verifyAuth(true, true, $this)) {
return;
}
try {
$this->getParams();
$this->setNewDatabaseConnection();
$this->createDatabaseTables();
} catch(Exception $e) {
$this->getResponse()
->setHttpResponseCode(400)
->appendBody($e->getMessage());
return;
}
$this->getResponse()
->setHttpResponseCode(201);
}
private function getParams() {
$this->dbuser = $this->_getParam('dbuser', '');
$this->dbpass = $this->_getParam('dbpass', '');
$this->dbname = $this->_getParam('dbname', '');
$this->dbhost = $this->_getParam('dbhost', '');
}
/**
* Set up a new database connection based on the parameters in the request
* @throws PDOException upon failure to connect
*/
private function setNewDatabaseConnection() {
self::$dbh = new PDO("pgsql:host=" . $this->dbhost
. ";dbname=" . $this->dbname
. ";port=5432" . ";user=" . $this->dbuser
. ";password=" . $this->dbpass);
$err = self::$dbh->errorInfo();
if ($err[1] != null) {
throw new PDOException("ERROR: Could not connect to database");
}
}
/**
* Install the Airtime database
* @throws Exception
*/
private function createDatabaseTables() {
$sqlDir = dirname(APPLICATION_PATH) . "/build/sql/";
$files = array("schema.sql", "sequences.sql", "views.sql", "triggers.sql", "defaultdata.sql");
foreach ($files as $f) {
try {
/*
* Unfortunately, we need to use exec here due to PDO's lack of support for importing
* multi-line .sql files. PDO->exec() almost works, but any SQL errors stop the import,
* so the necessary DROPs on non-existent tables make it unusable. Prepared statements
* have multiple issues; they similarly die on any SQL errors, fail to read in multi-line
* commands, and fail on any unescaped ? or $ characters.
*/
exec("export PGPASSWORD=" . $this->dbpass . " && psql -U " . $this->dbuser . " --dbname "
. $this->dbname . " -h " . $this->dbhost . " -f $sqlDir$f 2>/dev/null", $out, $status);
} catch (Exception $e) {
throw new Exception("ERROR: Failed to create database tables");
}
}
}
}