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