archive.drush.inc

  1. 8.0.x commands/core/archive.drush.inc
  2. 6.x commands/core/archive.drush.inc
  3. 7.x commands/core/archive.drush.inc
  4. 4.x commands/core/archive.drush.inc
  5. 5.x commands/core/archive.drush.inc
  6. master commands/core/archive.drush.inc

An early implementation of Site Archive dump/restore. See http://groups.drupal.org/site-archive-format.

Functions

Namesort descending Description
archive_archive_dump_complete Command argument complete callback.
archive_archive_restore_complete Command argument complete callback.
archive_drush_command
drush_archive_dump Command callback. Generate site archive file.
drush_archive_guess_manifest Try to find docroot and DB dump file in an extracted archive.
drush_archive_restore Command callback. Restore web site(s) from a site archive file.

File

commands/core/archive.drush.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * An early implementation of Site Archive dump/restore. See
  5. * http://groups.drupal.org/site-archive-format.
  6. */
  7. function archive_drush_command() {
  8. $items['archive-dump'] = array(
  9. 'description' => 'Backup your code, files, and database into a single file.',
  10. 'arguments' => array(
  11. 'sites' => 'Optional. Site specifications, delimited by commas. Typically, list subdirectory name(s) under /sites.',
  12. ),
  13. 'options' => array(
  14. 'description' => 'Describe the archive contents.',
  15. 'tags' => 'Add tags to the archive manifest. Delimit multiple by commas.',
  16. 'destination' => 'The full path and filename in which the archive should be stored. If omitted, it will be saved to the drush-backups directory and a filename will be generated.',
  17. 'overwrite' => 'Do not fail if the destination file exists; overwrite it instead.',
  18. 'generator' => 'The generator name to store in the MANIFEST file. The default is "Drush archive-dump".',
  19. 'generatorversion' => 'The generator version number to store in the MANIFEST file. The default is ' . DRUSH_VERSION . '.',
  20. 'pipe' => 'Only print the destination of the archive. Useful for scripts that don\'t pass --destination.',
  21. 'preserve-symlinks' => 'Preserve symbolic links.',
  22. 'no-core' => 'Exclude Drupal core, so the backup only contains the site specific stuff.',
  23. 'tar-options' => 'Options passed thru to the tar command.',
  24. ),
  25. 'examples' => array(
  26. 'drush archive-dump default,example.com,foo.com' => 'Write an archive containing 3 sites in it.',
  27. 'drush archive-dump @sites' => 'Save archive containing all sites in a multi-site.',
  28. 'drush archive-dump default --destination=/backups/mysite.tar' => 'Save archive to custom location.',
  29. 'drush archive-dump --tar-options="--exclude=.git --exclude=sites/default/files"' => 'Omits any .git directories found in the tree as well as sites/default/files.',
  30. 'drush archive-dump --tar-options="--exclude=%files"' => 'Placeholder %files is replaced with the real path for the current site, and that path is excluded.',
  31. ),
  32. 'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_SITE,
  33. 'aliases' => array('ard', 'archive-backup', 'arb'),
  34. );
  35. $items['archive-restore'] = array(
  36. 'description' => 'Expand a site archive into a Drupal web site.',
  37. 'arguments' => array(
  38. 'file' => 'The site archive file that should be expanded.',
  39. 'site name' => 'Optional. Which site within the archive you want to restore. Defaults to all.',
  40. ),
  41. 'required-arguments' => 1,
  42. 'options' => array(
  43. 'destination' => 'Specify where the Drupal site should be expanded, including the docroot. Defaults to the current working directory.',
  44. 'db-prefix' => 'An optional table prefix to use during restore.',
  45. 'db-url' => array(
  46. 'description' => 'A Drupal 6 style database URL indicating the target for database restore. If not provided, the archived settings.php is used.',
  47. 'example-value' => 'mysql://root:pass@host/db',
  48. ),
  49. 'db-su' => 'Account to use when creating the new database. Optional.',
  50. 'db-su-pw' => 'Password for the "db-su" account. Optional.',
  51. 'overwrite' => 'Allow drush to overwrite any files in the destination.',
  52. 'tar-options' => 'Options passed thru to the tar command.',
  53. ),
  54. 'examples' => array(
  55. 'drush archive-restore ./example.tar.gz' => 'Restore the files and databases for all sites in the archive.',
  56. 'drush archive-restore ./example.tar.gz example.com' => 'Restore the files and database for example.com site.',
  57. 'drush archive-restore ./example.tar.gz --destination=/var/www/example.com/docroot' => 'Restore archive to a custom location.',
  58. 'drush archive-restore ./example.tar.gz --db-url=mysql://root:pass@127.0.0.1/dbname' => 'Restore archive to a new database (and customize settings.php to point there.).',
  59. ),
  60. 'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
  61. 'aliases' => array('arr'),
  62. );
  63. return $items;
  64. }
  65. /**
  66. * Command callback. Generate site archive file.
  67. */
  68. function drush_archive_dump($sites_subdirs = '@self') {
  69. $include_platform = !drush_get_option('no-core', FALSE);
  70. $tar = drush_get_tar_executable();
  71. $sites = array();
  72. list($aliases, $not_found) = drush_sitealias_resolve_sitespecs(explode(',', $sites_subdirs));
  73. if (!empty($not_found)) {
  74. drush_log(dt("Some site subdirectories are not valid Drupal sites: @list", array("@list" => implode(', ', $not_found))), 'warning');
  75. }
  76. foreach ($aliases as $key => $alias) {
  77. $sites[$key] = $alias;
  78. if (($db_record = sitealias_get_databases_from_record($alias))) {
  79. $sites[$key]['databases'] = $db_record;
  80. }
  81. else {
  82. $sites[$key]['databases'] = array();
  83. drush_log(dt('DB definition not found for !alias', array('!alias' => $key)), 'notice');
  84. }
  85. }
  86. // The user can specify a destination filepath or not. That filepath might
  87. // end with .gz, .tgz, or something else. At the end of this command we will
  88. // gzip a file, and we want it to end up with the user-specified name (if
  89. // any), but gzip renames files and refuses to compress files ending with
  90. // .gz and .tgz, making our lives difficult. Solution:
  91. //
  92. // 1. Create a unique temporary base name to which gzip WILL append .gz.
  93. // 2. If no destination is provided, set $dest_dir to a backup directory and
  94. // $final_destination to be the unique name in that dir.
  95. // 3. If a destination is provided, set $dest_dir to that directory and
  96. // $final_destination to the exact name given.
  97. // 4. Set $destination, the actual working file we will build up, to the
  98. // unqiue name in $dest_dir.
  99. // 5. After gzip'ing $destination, rename $destination.gz to
  100. // $final_destination.
  101. //
  102. // Sheesh.
  103. // Create the unique temporary name.
  104. $prefix = 'none';
  105. if (!empty($sites)) {
  106. $first = current($sites);
  107. if ( !empty($first['databases']['default']['default']['database']) ) {
  108. $prefix = count($sites) > 1 ? 'multiple_sites' : str_replace('/', '-', $first['databases']['default']['default']['database']);
  109. }
  110. }
  111. $date = gmdate('Ymd_His');
  112. $temp_dest_name = "$prefix.$date.tar";
  113. $final_destination = drush_get_option('destination');
  114. if (!$final_destination) {
  115. // No destination provided.
  116. $backup = drush_include_engine('version_control', 'backup');
  117. // TODO: this standard drush pattern leads to a slightly obtuse directory structure.
  118. $dest_dir = $backup->prepare_backup_dir('archive-dump');
  119. if (empty($dest_dir)) {
  120. $dest_dir = drush_tempdir();
  121. }
  122. $final_destination = "$dest_dir/$temp_dest_name.gz";
  123. }
  124. else {
  125. // Use the supplied --destination. If it is relative, resolve it
  126. // relative to the directory in which drush was invoked.
  127. $command_cwd = getcwd();
  128. drush_op('chdir', drush_get_context('DRUSH_OLDCWD', getcwd()));
  129. // This doesn't perform realpath on the basename, but that's okay. This is
  130. // not path-based security. We just use it for checking for perms later.
  131. drush_mkdir(dirname($final_destination));
  132. $dest_dir = realpath(dirname($final_destination));
  133. $final_destination = $dest_dir . '/' . basename($final_destination);
  134. drush_op('chdir', $command_cwd);
  135. }
  136. // $dest_dir is either the backup directory or specified directory. Set our
  137. // working file.
  138. $destination = "$dest_dir/$temp_dest_name";
  139. // Validate the FINAL destination. It should be a file that does not exist
  140. // (unless --overwrite) in a writable directory (and a writable file if
  141. // it exists). We check all this up front to avoid failing after a long
  142. // dump process.
  143. $overwrite = drush_get_option('overwrite');
  144. $dest_dir = dirname($final_destination);
  145. $dt_args = array('!file' => $final_destination, '!dir' => $dest_dir);
  146. if (is_dir($final_destination)) {
  147. drush_set_error('DRUSH_ARCHIVE_DEST_IS_DIR', dt('Destination !file must be a file, not a directory.', $dt_args));
  148. return;
  149. }
  150. else if (file_exists($final_destination)) {
  151. if (!$overwrite) {
  152. drush_set_error('DRUSH_ARCHIVE_DEST_EXISTS', dt('Destination !file exists; specify --overwrite to overwrite.', $dt_args));
  153. return;
  154. }
  155. else if (!is_writable($final_destination)) {
  156. drush_set_error('DRUSH_ARCHIVE_DEST_FILE_NOT_WRITEABLE', dt('Destination !file is not writable.', $dt_args));
  157. return;
  158. }
  159. }
  160. else if (!is_writable($dest_dir)) {
  161. drush_set_error('DRUSH_ARCHIVE_DEST_DIR_NOT_WRITEABLE', dt('Destination directory !dir is not writable.', $dt_args));
  162. return;
  163. }
  164. // Get the extra options for tar, if any
  165. $tar_extra_options = drush_sitealias_evaluate_paths_in_options(drush_get_option('tar-options', ''));
  166. // Start adding codebase to the archive.
  167. $docroot_path = realpath(drush_get_context('DRUSH_DRUPAL_ROOT'));
  168. $docroot = basename($docroot_path);
  169. $workdir = dirname($docroot_path);
  170. if ($include_platform) {
  171. $dereference = (drush_get_option('preserve-symlinks', FALSE)) ? '' : '--dereference ';
  172. // Convert destination path to Unix style for tar on MinGW - see http://drupal.org/node/1844224
  173. if (drush_is_mingw()) {
  174. $destination_orig = $destination;
  175. $destination = str_replace('\\', '/', $destination);
  176. $destination = preg_replace('$^([a-zA-Z]):$', '/$1', $destination);
  177. }
  178. // Archive Drupal core, excluding sites dir.
  179. drush_shell_cd_and_exec($workdir, "$tar {$tar_extra_options} --exclude \"{$docroot}/sites\" {$dereference}-cf %s %s", $destination, $docroot);
  180. // Add sites/all to the same archive.
  181. drush_shell_cd_and_exec($workdir, "$tar {$tar_extra_options} {$dereference}-rf %s %s", $destination, "{$docroot}/sites/all");
  182. // Add special files in sites/ to the archive.
  183. $files_to_add = array('sites/README.txt', 'sites/sites.php', 'sites/example.sites.php');
  184. foreach ($files_to_add as $file_to_add) {
  185. if (file_exists($file_to_add)) {
  186. drush_shell_cd_and_exec($workdir, "$tar {$dereference}-rf %s %s", $destination, $docroot . '/' . $file_to_add);
  187. }
  188. }
  189. }
  190. $tmp = drush_tempdir();
  191. $all_dbs = array();
  192. // Dump the default database for each site and add to the archive.
  193. foreach ($sites as $key => $alias) {
  194. if (isset($alias['databases']['default']['default'])) {
  195. $db = $alias['databases']['default']['default'];
  196. // Use a subdirectory name matching the docroot name.
  197. drush_mkdir("{$tmp}/{$docroot}");
  198. // Ensure uniqueness by prefixing key if needed. Remove path delimiters.
  199. $dbname = str_replace(DIRECTORY_SEPARATOR, '-', $db['database']);
  200. $result_file = count($sites) == 1 ? "$tmp/$dbname.sql" : str_replace('@', '', "$tmp/$key-$dbname.sql");
  201. $all_dbs[$key] = array(
  202. 'file' => basename($result_file),
  203. 'driver' => $db['driver'],
  204. );
  205. $table_selection = drush_sql_get_expanded_table_selection(drush_sitealias_get_db_spec($alias));
  206. list($dump_exec, $dump_file) = drush_sql_build_dump_command($table_selection, $db, $result_file);
  207. if (!drush_shell_exec($dump_exec)) {
  208. return drush_set_error('DRUSH_SQL_DUMP_FAIL', 'Database dump failed.');
  209. }
  210. drush_shell_cd_and_exec($tmp, "$tar {$tar_extra_options} --dereference -rf %s %s", $destination, basename($result_file));
  211. }
  212. }
  213. // Build a manifest file AND add sites/$subdir to archive as we go.
  214. $platform = array(
  215. 'datestamp' => time(),
  216. 'formatversion' => '1.0',
  217. 'generator' => drush_get_option('generator', 'Drush archive-dump'),
  218. 'generatorversion' => drush_get_option('generatorversion', DRUSH_VERSION),
  219. 'description' => drush_get_option('description', ''),
  220. 'tags' => drush_get_option('tags', ''),
  221. 'archiveformat' => ($include_platform ? 'platform' : 'site'),
  222. );
  223. $contents = drush_export_ini(array('Global' => $platform));
  224. $i=0;
  225. foreach ($sites as $key => $alias) {
  226. if (!$status = drush_invoke_process($alias, 'core-status', array(), array(), array('integrate' => FALSE))) {
  227. drush_log(dt('Unable to determine sites directory for !alias', array('!alias' => $key)), 'warning');
  228. }
  229. // Add the site specific directory to archive.
  230. if (!empty($status['object']['%paths']['%site'])) {
  231. drush_shell_cd_and_exec($workdir, "$tar {$tar_extra_options} --dereference -rf %s %s", $destination, "{$docroot}/sites/" . basename($status['object']['%paths']['%site']));
  232. }
  233. $site = array(
  234. 'docroot' => DRUPAL_ROOT,
  235. 'sitedir' => @$status['object']['%paths']['%site'],
  236. 'files-public' => @$status['object']['%paths']['%files'],
  237. 'files-private' => @$status['object']['%paths']['%private'],
  238. );
  239. $site["database-default-file"] = $all_dbs[$key]['file'];
  240. $site["database-default-driver"] = $all_dbs[$key]['driver'];
  241. // The section title is the sites subdirectory name.
  242. $info[basename($site['sitedir'])] = $site;
  243. $contents .= "\n" . drush_export_ini($info);
  244. unset($info);
  245. $i++;
  246. }
  247. file_put_contents("{$tmp}/MANIFEST.ini", $contents);
  248. // Add manifest to archive.
  249. drush_shell_cd_and_exec($tmp, "$tar --dereference -rf %s %s", $destination, 'MANIFEST.ini');
  250. // Ensure that default/default.settings.php is in the archive. This is needed
  251. // by site-install when restoring a site without any DB.
  252. // NOTE: Windows tar file replace operation is broken so we have to check if file already exists.
  253. // Otherwise it will corrupt the archive.
  254. $res = drush_shell_cd_and_exec($workdir, "$tar -tf %s %s", $destination, $docroot . '/sites/default/default.settings.php');
  255. $output = drush_shell_exec_output();
  256. if (!$res || !isset($output[0]) || empty($output[0])) {
  257. drush_shell_cd_and_exec($workdir, "$tar --dereference -vrf %s %s", $destination, $docroot . '/sites/default/default.settings.php');
  258. }
  259. // Switch back to original destination in case it was modified for tar on MinGW.
  260. if (!empty($destination_orig)) {
  261. $destination = $destination_orig;
  262. }
  263. // Compress the archive
  264. drush_shell_exec("gzip --no-name -f %s", $destination);
  265. // gzip appends .gz unless the name already ends in .gz, .tgz, or .taz.
  266. if ("{$destination}.gz" != $final_destination) {
  267. drush_move_dir("{$destination}.gz", $final_destination, $overwrite);
  268. }
  269. drush_log(dt('Archive saved to !dest', array('!dest' => $final_destination)), 'ok');
  270. return $final_destination;
  271. }
  272. /**
  273. * Command argument complete callback.
  274. *
  275. * @return
  276. * List of site names/aliases for archival.
  277. */
  278. function archive_archive_dump_complete() {
  279. return array('values' => array_keys(_drush_sitealias_all_list()));
  280. }
  281. /**
  282. * Command callback. Restore web site(s) from a site archive file.
  283. */
  284. function drush_archive_restore($file, $site_id = NULL) {
  285. $tmp = drush_tempdir();
  286. // Get the extra options for tar, if any
  287. $tar_extra_options = drush_sitealias_evaluate_paths_in_options(drush_get_option('tar-options', ''));
  288. if (!$files = drush_tarball_extract($file, $tmp, FALSE, $tar_extra_options)) {
  289. return drush_set_error('DRUSH_ARCHIVE_UNABLE_TO_EXTRACT', dt('Unable to extract site archive tarball to !tmp.', array('!tmp' => $tmp)));
  290. }
  291. $manifest = $tmp . '/MANIFEST.ini';
  292. if (file_exists($manifest)) {
  293. if (!$ini = parse_ini_file($manifest, TRUE)) {
  294. return drush_set_error('DRUSH_ARCHIVE_UNABLE_TO_PARSE_MANIFEST', dt('Unable to parse MANIFEST.ini in the archive.'));
  295. }
  296. }
  297. else {
  298. $ini = drush_archive_guess_manifest($tmp);
  299. }
  300. // Backward compatibility: 'archiveformat' did not exist
  301. // in older versions of archive-dump.
  302. if (!isset( $ini['Global']['archiveformat'])) {
  303. $ini['Global']['archiveformat'] = 'platform';
  304. }
  305. // Grab the first site in the Manifest and move docroot to destination.
  306. $ini_tmp = $ini;
  307. unset($ini_tmp['Global']);
  308. $first = array_shift($ini_tmp);
  309. $docroot = basename($first['docroot']);
  310. $destination = drush_get_option('destination', realpath('.') . "/$docroot");
  311. if ($ini['Global']['archiveformat'] == 'platform') {
  312. // Move the whole platform inplace at once.
  313. if (!drush_move_dir("$tmp/$docroot", $destination, drush_get_option('overwrite'))) {
  314. return drush_set_error('DRUSH_ARCHIVE_UNABLE_TO_RESTORE_FILES', dt('Unable to restore platform to !dest', array('!dest' => $destination)));
  315. }
  316. }
  317. else {
  318. // When no platform is included we do this on a per-site basis.
  319. }
  320. // Loop over sites and restore databases and append to settings.php.
  321. foreach ($ini as $section => $site) {
  322. if ($section != 'Global' && (!isset($site_id) || $section == $site_id) && !empty($site['database-default-file'])) {
  323. $site_destination = $destination . '/' . $site['sitedir'];
  324. // Restore site, in case not already done above.
  325. if ($ini['Global']['archiveformat'] == 'site') {
  326. if (!drush_move_dir("$tmp/$docroot/" . $site['sitedir'], $site_destination, drush_get_option('overwrite'))) {
  327. return drush_set_error('DRUSH_ARCHIVE_UNABLE_TO_RESTORE_FILES', dt('Unable to restore site to !dest', array('!dest' => $site_destination)));
  328. }
  329. }
  330. // Restore database.
  331. $sql_file = $tmp . '/' . $site['database-default-file'];
  332. if ($db_url = drush_get_option('db-url')) {
  333. if (empty($site_id) && count($ini) >= 3) {
  334. // TODO: Use drushrc to provide multiple db-urls for multi-restore?
  335. return drush_set_error('DRUSH_ARCHIVE_UNABLE_MULTI_RESTORE', dt('You must specify a site to restore when the archive contains multiple sites and a db-url is provided.'));
  336. }
  337. $db_spec = drush_convert_db_from_db_url($db_url);
  338. }
  339. else {
  340. $site_specification = $destination . '#' . $section;
  341. if ($return = drush_invoke_process($site_specification, 'sql-conf', array(), array('all' => TRUE), array('integrate' => FALSE, 'override-simulated' => TRUE))) {
  342. $databases = $return['object'];
  343. $db_spec = $databases['default']['default'];
  344. }
  345. else {
  346. return drush_set_error('DRUSH_ARCHIVE_UNABLE_DISCOVER_DB', dt('Unable to get database details from db-url option or settings.php', array('!key' => $key)));
  347. }
  348. }
  349. drush_sql_empty_db($db_spec);
  350. _drush_sql_query(NULL, $db_spec, $sql_file);
  351. // Append new DB info to settings.php.
  352. if ($db_url) {
  353. $settingsfile = $destination . '/' . $site['sitedir'] . '/settings.php';
  354. //If settings.php doesn't exist in the archive, create it from default.settings.php.
  355. if (!file_exists($settingsfile)) {
  356. drush_op('copy', $destination . '/sites/default/default.settings.php', $settingsfile);
  357. }
  358. // Need to do something here or else we can't write.
  359. chmod($settingsfile, 0664);
  360. file_put_contents($settingsfile, "\n// Appended by drush archive-restore command.\n", FILE_APPEND);
  361. if (drush_drupal_major_version($destination) >= 7) {
  362. file_put_contents($settingsfile, "\n" . '$databases = ' . var_export(drush_sitealias_convert_db_from_db_url($db_url), TRUE) . ";\n", FILE_APPEND);
  363. }
  364. else {
  365. file_put_contents($settingsfile, "\n" . '$db_url = \'' . $db_url . "';\n", FILE_APPEND);
  366. }
  367. drush_log(dt('Drush appended the new database configuration at settings.php. Optionally remove the old configuration manually.'), 'ok');
  368. }
  369. }
  370. }
  371. drush_log(dt('Archive restored to !dest', array('!dest' => $destination)), 'ok');
  372. return $destination;
  373. }
  374. /**
  375. * Command argument complete callback.
  376. *
  377. * @return
  378. * Strong glob of files to complete on.
  379. */
  380. function archive_archive_restore_complete() {
  381. return array(
  382. 'files' => array(
  383. 'directories' => array(
  384. 'pattern' => '*',
  385. 'flags' => GLOB_ONLYDIR,
  386. ),
  387. 'tar' => array(
  388. 'pattern' => '*.tar.gz',
  389. ),
  390. ),
  391. );
  392. }
  393. /**
  394. * Try to find docroot and DB dump file in an extracted archive.
  395. *
  396. * @param string $path The location of the extracted archive.
  397. * @return array The manifest data.
  398. */
  399. function drush_archive_guess_manifest($path) {
  400. $db_file = drush_scan_directory($path, '/\.sql$/', array('.', '..', 'CVS'), 0, 0);
  401. if (file_exists($path . '/index.php')) {
  402. $docroot = './';
  403. }
  404. else {
  405. $directories = glob($path . '/*' , GLOB_ONLYDIR);
  406. $docroot = reset($directories);
  407. }
  408. $ini = array(
  409. 'Global' => array(
  410. // Very crude detection of a platform...
  411. 'archiveformat' => (drush_drupal_version($docroot) ? 'platform' : 'site'),
  412. ),
  413. 'default' => array(
  414. 'docroot' => $docroot,
  415. 'sitedir' => 'sites/default',
  416. 'database-default-file' => key($db_file),
  417. ),
  418. );
  419. return $ini;
  420. }