command to execute} {--snapshot= : provide name of snapshot}'; /** * The console command description. * * @var string */ protected $description = 'Daily MySQL Backup'; /** * Execute the console command. * * @return mixed */ public function handle() { switch ($this->option('command')) { case 'create': $this->takeSnapShot(); break; case 'restore': //$this->restoreSnapShot(); break; default: $this->error("Invalid Option !!"); break; } } /** * Function takes regular backup * for mysql database.. * */ private function takeSnapShot() { ini_set('max_execution_time', -1); set_time_limit(0); ini_set('memory_limit', '-1'); // define target file $name = env('DB_DATABASE') . '_' . date("Y-m-d_Hi"); $tempLocation = '/tmp/' .$name. '.sql.gz'; $targetFilePath = '/mysql/' .$name. '.sql.gz'; // run the cli job $process = new Process('mysqldump -h' ._env('DB_HOST_READONLY'). ' -u' ._env('DB_USERNAME'). ' -p' ._env('DB_PASSWORD'). ' ' ._env('DB_DATABASE'). ' --ignore-table='._env('DB_DATABASE').'.consumer_api_requests | gzip > ' .$tempLocation); $process->run(); try { if ($process->isSuccessful()) { $s3 = Storage::disk('s3'); $s3->put($targetFilePath, file_get_contents($tempLocation), 'private'); unlink($tempLocation); event(new EventSendDbBackupEmail('mysql-backup',1)); /*$current_timestamp = time() - (72 * 3600); $allFiles = $s3->allFiles(env('APP_ENV')); foreach ($allFiles as $file) { // delete the files older then 3 days.. if ( $s3->lastModified($file) <= $current_timestamp ) { $s3->delete($file); $this->info("File: {$file} deleted."); } }*/ } else { throw new ProcessFailedException($process); } @unlink($tempLocation); } catch (\Exception $e) { $this->info('Exception occurred : MySQL Command running issue'); } } /** * Function restore given snapshot * for mysql database */ private function restoreSnapShot() { $snapshot = $this->option('snapshot'); if(!$snapshot) { $this->error("snapshot option is required."); } try { // get file from s3 $s3 = Storage::disk('s3'); $found = $s3->get('/mysql/' .$snapshot. '.sql'); $tempLocation = '/tmp/' .env('DB_DATABASE') . '_' . date("Y-m-d_Hi") . '.sql'; // create a temp file $bytes_written = File::put($tempLocation, $found); if ($bytes_written === false) { $this->info("Error writing to file: " .$tempLocation); } // run the cli job $process = new Process("mysql -h " .env('DB_HOST'). " -u " .env('DB_USERNAME'). " -p" .env('DB_PASSWORD'). " ".env('DB_DATABASE'). " < {$tempLocation}"); $process->run(); //@unlink($tempLocation); if ($process->isSuccessful()) { $this->info("Restored snapshot: " .$snapshot); } else { throw new ProcessFailedException($process); } } catch (\Exception $e) { $this->info('Exception occurred : MySQL Command running issue'); } } }