db.drush.inc 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php
// $Id$
/**
 * @file
 *    Mysql provisioning module.
 *
 * The goal of this module is to create mysql databases and user accounts, for sites that are about to be created.
 * It uses the provision API to tie into the right places in the site creation work flow.
 */

11

Adrian Rossouw's avatar
Adrian Rossouw committed
12 13
include_once(dirname(__FILE__) . '/../provision.service.inc');

14
function db_drush_init($url = null) {
15
  // todo same as http, consolidate
16 17 18
  $command = drush_get_command();
  $command = explode(" ", $command['command']);
  if (preg_match("/^provision-/", $command[0])) {
19
    _provision_context_init($url);
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

    if (PROVISION_CONTEXT_SERVER) {
      if (!is_null(drush_get_option('init_db'))) {
        // Bootstrap for alias creation.
        include_once(drush_get_option('init_db') . '/'. drush_get_option('init_db') .'_service.inc');
        $class = 'provisionService_db_' . drush_get_option('init_db');
        provision_service('db', new $class());
      }
    }
    else {
      // todo should be constructed based on drush aliases
      include_once('mysql/mysql_service.inc');
      provision_service('db', new provisionService_db_mysql());
    }
  }

  // this is where we generate the db service object.
}

function db_drush_exit() {
  // determine how to close it too.
  provision_service('db')->close();
}



function db_drush_help($section) {
  switch ($section) {
    case 'error:PROVISION_CREATE_DB_FAILED' :
      return dt('Unable to create new databases.');
    case 'error:PROVISION_DROP_DB_FAILED' :
      return dt('Unable to drop database.');
  }
}


class provisionService_db extends provisionService {
  function __construct() {
58 59
    $master_db = drush_get_option('master_db');

60 61 62 63 64 65
    if ($master_db) {
      $db = parse_url($master_db);
      $host = urldecode($db['host']);
      $user = urldecode($db['user']);
      $pass = urldecode($db['pass']);
      $scheme = $db['scheme'];
drumm's avatar
drumm committed
66 67
    }
    else {
68 69 70 71 72 73 74 75 76
      #TODO - this stuff is all pretty wrong imo. it should not be asked here
      drush_print(dt("No database configuration provided, asking for one interactively"));
      $scheme = drush_prompt(dt("Database type"), "mysql");
      $host = drush_prompt(dt("Database server"), "localhost");
      $user = drush_prompt(dt("Database user"), "root");
      system('stty -echo');
      $pass = drush_prompt(dt("Database password"));
      system('stty echo');
      print "\n"; # add a cr since the user's didn't echo
77
      drush_set_option('master_db', "$scheme://$user:$pass@$host", 'user');
78 79 80 81 82 83 84 85 86 87
    }

    drush_set_default('master_db_user', $user);
    drush_set_default('master_db_passwd', $pass);

    drush_set_default('master_db_host', $host);
    drush_set_default('db_host', $host);

    drush_set_default('master_db_type', $scheme);
    drush_set_default('db_type', $scheme);
88 89 90 91 92 93

    $creds = array();
    $options = array(
      'master_db_user' => 'user',
      'master_db_passwd' => 'pass',
      'master_db_host' => 'host',
drumm's avatar
drumm committed
94 95
      'master_db_type' => 'type',
    );
96 97 98 99

    foreach ($options as $option => $key) {
      $creds[$key] = drush_get_option($option, '');
    }
100 101 102
    $this->creds = $creds;
  }

103 104 105 106 107 108 109 110 111
  function verify() { 
    if (!$this->can_create_database()) {
      drush_set_error('PROVISION_CREATE_DB_FAILED');
    }
    else {
      drush_log(dt('Provision can create new databases.'), 'message');
    }
  }

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  /**
   * Find a viable database name, based on available information.
   *
   * This function exists solely to work past mysql's database name restrictions.
   * As mysql also does not have the ability to rename databases, it is completely
   * possible that sites will be running with derivative names on the same server,
   * until the upgrade / restore process is completed.
   *
   * TODO: abstract this properly.
   */ 
  function suggest_db_name($url) {
    if ($sid = drush_get_option('site_id')) {
      $suggest_base = drush_get_option('aegir_db_prefix', 'site_') . $sid;
    }
    elseif ($name = drush_get_option('db_name')) {
      // consider the verified database name if no site id was provided
      //
      // we strip out eventual _N suffixes before finding a new db name
      // this is necessary because we may already have gone through this
      // process (in a migration) and had a _N suffix added
      $suggest_base = preg_replace('/_\d+$/', '', $name);
    }
    else {
      // This is a last option, and not ideal: base the db name on the
      // site name
      //
      // Provision only users will trigger this mostly.
      $suggest_base = substr(str_replace(array(".", "-"), '' , ereg_replace("^www\.", "", $url)), 0, 14);
    }
    $suggest[] = $suggest_base;
    for ($i = 0; $i < 100; $i++) {
      $suggest[] = $suggest_base .'_'. $i;
    }

    foreach ($suggest as $option) {
      if (!$this->database_exists($option)) {
        return $option;
      }
    }

    drush_set_error('PROVISION_CREATE_DB_FAILED', dt("Could not find a free database names after 100 attempts"));
    return false;

  }


  /**
   * Generate a new mysql database and user account for the specified credentials
   */
  function create_site_database($url) {
162
    $creds = $this->generate_site_credentials($url);
163 164 165 166 167 168 169 170 171 172 173 174 175 176
    extract($creds);
    

    if (!$this->can_create_database()) {
     drush_set_error('PROVISION_CREATE_DB_FAILED');
     drush_log("Database could not be created.", 'error');
     return FALSE;
    }


    drush_log(dt("Granting privileges to %user@%client on %database", array('%user' => $db_user, '%client' => $db_grant_host, '%database' => $db_name)));


    if (!$this->grant($db_name, $db_user, $db_passwd, $db_grant_host)) {
177
      drush_set_error('PROVISION_CREATE_DB_FAILED', dt(("Could not create database user @user", array('@user' => $db_user)));
178 179
    }

180
    $this->create_database($db_name);
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    $status = $this->database_exists($db_name);

    if ($status) {
      drush_log(dt('Created @name database', array("@name" => $db_name)), 'success');
    }
    else {
      drush_set_error('PROVISION_CREATE_DB_FAILED', dt("Could not create @name database", array("@name" => $db_name)));
    }
    return $status; 
  }


  
  /**
   * Remove the database and user account for the supplied credentials
   */
  function destroy_site_database($url) {
    $creds = $this->fetch_site_credentials();
    extract($creds);

    if ( $this->database_exists($db_name) ) {
      drush_log(dt("Dropping database @dbname", array('@dbname' => $db_name)));
      if (!$this->drop_database($db_name)) {
        drush_log(dt("Failed to drop database @dbname", array('@dbname' => $db_name)), 'warning');
      }
    }
    
    if ( $this->database_exists($db_name) ) {
     drush_set_error('PROVISION_DROP_DB_FAILED');
     return FALSE;
    }
    
    drush_log(dt("Revoking privileges of %user@%client from %database", array('%user' => $db_user, '%client' => $db_grant_host, '%database' => $db_name)));
    if (!$this->revoke($db_name, $db_user, $db_grant_host)) {
      drush_log(dt("Failed to revoke user privileges"), 'warning');
    }
  }


  function import_site_database($url) {
    $dump_file = drush_get_option('sites_path') .'/'. $url .'/database.sql';

    $creds = $this->fetch_site_credentials();

225 226 227 228
    $exists = provision_service('file')->exists($dump_file)
      ->succeed('Found database dump at @path.')
      ->fail('No database dump was found at @path.', 'PROVISION_DB_DUMP_NOT_FOUND')
      ->status();
229
    if ($exists) {
230 231 232 233
      $readable = provision_service('file')->readable($dump_file)
        ->succeed('Database dump at @path is readable')
        ->fail('The database dump at @path could not be read.', 'PROVISION_DB_DUMP_NOT_READABLE')
        ->status();
234 235 236 237 238 239 240 241 242
      if ($readable) {
        $this->import_dump($dump_file, $creds);
      }
    }
  }


  // todo - SORT THIS SHIT OUT!
  function dump_site_database($url) {
243
    return $this->generate_dump($url);
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
  }


  function generate_site_credentials($url) {
    $creds = array();
    // replace with service type 
    $db_type = drush_get_option('db_type');
    // As of Drupal 7 there is no more mysqli type
    if (drush_drupal_major_version() >= 7) {
      $db_type = ($db_type == 'mysqli') ? 'mysql' : $db_type;
    }

    //TODO - this should not be here at all
    $creds['db_type'] = drush_set_option('db_type', $db_type, 'site');
    $creds['db_host'] = drush_set_option('db_host', drush_get_option('db_host'), 'site');
    $creds['db_passwd'] = drush_set_option('db_passwd', provision_password(), 'site');
    $creds['db_name'] = drush_set_option('db_name', $this->suggest_db_name($url), 'site');
261
    $creds['db_user'] = drush_set_option('db_user', $creds['db_name'], 'site');
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    $creds['db_grant_host'] = $this->grant_host();

    return $creds;
  }

  function fetch_site_credentials($url) {
    $creds = array();

    $keys = array('db_type', 'db_user', 'db_name', 'db_host', 'db_passwd');
    foreach ($keys as $key) {
      $creds[$key] = drush_get_option($key, '', 'site');
    }

    $creds['db_grant_host'] = $this->grant_host();
    return $creds;
  }

  function database_exists($name) {
    return FALSE;
  }

  function drop_database($name) {
    return FALSE;
  }

  function create_database($name) {
    return FALSE;
  }

  function can_create_database() { 
    return FALSE;
  }

  function grant($name, $username, $password, $host = '') {
    return FALSE;
  }

  function revoke($name, $username, $host = '') {
    return FALSE;
  }

  function import_dump($dump_file, $creds) {
    return FALSE;
  }

  function generate_dump($url) {
    return FALSE;
  }

311
  function grant_host() {
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    return 'localhost';
  }

}




/**
 * Indicates the place holders that should be replaced in _db_query_callback().
 */
define('PROVISION_QUERY_REGEXP', '/(%d|%s|%%|%f|%b)/');



// simple wrapper class for PDO based db services

class provisionService_db_pdo extends provisionService_db {
  public $conn;
  protected $creds;
  private $dsn;

334 335
  function __construct() {
    parent::__construct();
336

337
    $this->dsn = sprintf("%s:host=%s", $this->PDO_type,  $this->creds['host']);
338 339 340 341
  }

  function connect() {
    try {
342
      $this->conn = new PDO($this->dsn, $this->creds['user'], $this->creds['pass']);
343 344 345 346 347 348 349 350 351 352
    }
    catch (PDOException $e) {
      return drush_set_error('PROVISION_DB_CONNECT_FAIL', $e->getMessage());
    }
  } 

  function close() {
    $this->conn = null;
  }

353
  function query($query) {
354 355 356 357 358 359 360
    $args = func_get_args();
    array_shift($args);
    if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
      $args = $args[0];
    }
    $this->query_callback($args, TRUE);
    $query = preg_replace_callback(PROVISION_QUERY_REGEXP, array($this, 'query_callback'), $query);
361
    
362 363 364
    try {
      $result = $this->conn->query($query);
    }
365
    catch (PDOException $e) {
366 367 368 369 370 371 372 373
      drush_log($e->getMessage(), 'warning');
      return FALSE;
    } 

    return $result;

  }

374
  function query_callback($match, $init = FALSE) {
375 376 377 378 379 380 381 382 383 384
    static $args = NULL;
    if ($init) {
      $args = $match;
      return;
    }

    switch ($match[1]) {
      case '%d': // We must use type casting to int to convert FALSE/NULL/(TRUE?)
        return (int) array_shift($args); // We don't need db_escape_string as numbers are db-safe
      case '%s':
385
        return substr($this->conn->quote(array_shift($args)), 1, -1);
386 387 388 389 390 391 392 393 394 395 396
      case '%%':
        return '%';
      case '%f':
        return (float) array_shift($args);
      case '%b': // binary data
        return $this->conn->quote(array_shift($args));
    }

  }
}