Debian Codegraph @

src/commandline.cpp

raw symbols SCIP
1 /*-------------------------commandline.cpp------------------------------------------
2 runs luckybackup in command line mode
3
4 ===============================================================================================================================
5 ===============================================================================================================================
6 This file is part of "luckyBackup" project
7 Copyright, Loukas Avgeriou
8 luckyBackup is distributed under the terms of the GNU General Public License
9 luckyBackup is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 luckyBackup is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with luckyBackup. If not,see <http://www.gnu.org/licenses/>.
21 developer : luckyb
22 last modified : 22 May 2016
23 ===============================================================================================================================
24 ===============================================================================================================================
25 */
26
27 //#include "luckybackupwindow.cpp"
28 #include "commandline.h"
29
30 #include <QProcess>
31 #include <QTextStream>
32
33 #include "global.h"
34 #include "operationClass.h"
35
36 // class commandline Constructor=================================================================================================
37 commandline::commandline()
38 {
39 writeToLog=false;
40 errorsFound = 0; // Total number of errors from all tasks (in CLI, only 1 error per task is allowed !!)
41 filesTransfered = 0; //total bytes transfered during profile execution
42 bytesTransfered = 0; //total bytes transfered during profile execution
43 errorCount = 0; // Number of errors from one task (max value is 1)
44 }
45
46 // class commandline Destructor=================================================================================================
47 commandline::~commandline()
48 {
49 }
50
51 // result===================================================================================================================
52 // calls functions intro, loadProfile, check_list, check_dirs, rsyncIT, thats_all and returns an integer to main()
53 int commandline::result()
54 {
55 intro();
56
57 rsyncIT();
58 thats_all();
59
60 if (errorsFound > 0)
61 return 6; // error at rsync or pre/post command execution
62
63 return 0;
64 }
65
66 // intro===================================================================================================================
67 // displays an intro message
68 void commandline::intro()
69 {
70 cout << "\n============================================================================================\n";
71 cout << " luckybackup version ";
72 cout << appVersion;
73 cout << " - command line mode \n";
74 cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n";
75 cout << "This application will (hopefully) sync and backup everything you need in no time\n";
76 cout << "(Well, it might take a little longer if run for the first time ;-)\n\n";
77 cout << "\n";
78 if (!NoQuestions) //if questions are required
79 {
80 cout << "Make sure that:\n";
81 cout << "You have already declared and mounted all the directories that need to be synced/backed-up\n";
82 cout << "Please take a moment to examine all messages from checks done until now\n\n";
83 cout << "Also have in mind that, to avoid errors, it is best to run this app as su\n\n";
84 cout << "Hit 'enter' to continue otherwise press 'ctrl+c' to exit NOW\n";
85 cin.get();
86 }
87 cout << "\n\n";
88 }
89
90
91
92 // rsyncIT===================================================================================================================
93 // Performs the execution of operations
94 void commandline::rsyncIT()
95 {
96 cout << "\n============================================================================================\n";
97 cout << " Executing tasks";
98 if (DryRun)
99 cout << " (simulation mode)";
100 cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n";
101
102 //some useful variables-----------------------------------------------------------------------
103 QProcess *syncProcess; syncProcess = new QProcess; //create a new qprocess (for rsync)
104 QString command = rsyncCommandPath; //command to be executed. Normally this is "rsync"
105 QString command2=""; // windows use
106 QStringList rsyncArguments; // This stringList holds all arguments for the rsync command
107 QString dirA; //holds the first dir to be synced
108 QString dirB; //holds the second dir to be synced
109 QString logText=""; //This text will be appended to the logfile
110
111 currentOperation = 0;
112
113 while (currentOperation < TotalOperations)
114 {
115 if (WINrunning)
116 {
117 setAppDir(Operation[currentOperation] -> GetLuckyBackupDir());
118 /* disable vss until...
119 pipeVssFile = new QFile(Operation[currentOperation] -> GetTempPath()+SLASH+"qt_tempvss"+QString::number(qrand() % (999998) + 1));
120 if (pipeVssFile->open(QIODevice::ReadWrite)){
121 pipeVssFile->close();
122 }
123 pipeVssErrFile = new QFile(Operation[currentOperation] -> GetTempPath()+SLASH+"qt_tempvsserr"+QString::number(qrand() % (999998) + 1));
124 if (pipeVssErrFile->open(QIODevice::ReadWrite)){
125 pipeVssErrFile->close();
126 }*/
127 }
128
129 //if --skip-critical is given as argument and the task is CRITICAL
130 if ( (Operation[currentOperation] -> GetCRITICAL()) && (SkipCritical) )
131 Operation[currentOperation] -> SetPerform(false); //don't perform this operation
132
133 if ( (Operation[currentOperation] -> GetPerform()) || (Operation[currentOperation] -> GetByPassWARNING()) )
134 {
135 bool RemoteDestUsed = (Operation[currentOperation] -> GetRemoteDestination()) && (Operation[currentOperation] -> GetRemote());
136
137 // SNAPSHOTS REMOVAL - This is outside the (currentSnaps >= maxSnaps) condition, because it will eventually cause the snapshots directory to get created so that the profile will be backed up without problems later on
138 // First calculate the folder where snapshots go
139 QStringList tempArguments = Operation[currentOperation] -> GetArgs();
140 QString tempSource = tempArguments[tempArguments.size()-2];
141 QString tempDestination = tempArguments[tempArguments.size()-1];
142 QString tempDestinationOrig = tempArguments[tempArguments.size()-1]; //windows use
143 QString tempDestinationOrig2;
144 QString sourceLast = tempSource;
145
146 // win stuff ~~~~~
147 QString tslash;
148 if (WINrunning)
149 tslash=XnixSLASH;
150 else
151 tslash=SLASH;
152
153 if (!tempSource.endsWith(SLASH)) // this means task is of type "backup dir by name"
154 {
155 sourceLast = calculateLastPath(sourceLast); // This is the lowest dir of the source
156
157 tempSource.append(SLASH);
158
159 if (WINrunning && RemoteDestUsed)
160 tempDestination.append(sourceLast + XnixSLASH);
161 else
162 tempDestination.append(sourceLast + SLASH);
163 }
164
165 tempDestinationOrig2=tempDestination;
166 if (RemoteDestUsed && WINrunning)
167 tempDestination.append (snapDefaultDir.replace(SLASH,XnixSLASH));
168 else
169 tempDestination.append (snapDefaultDir);
170
171 QStringList remoteArgs; remoteArgs.clear();
172 //all remote arguments exactly as used at normal backup
173 if (RemoteDestUsed)
174 {
175 remoteArgs.append("--protect-args");
176 if ( (Operation[currentOperation]-> GetRemoteModule()) && (Operation[currentOperation] -> GetRemotePassword() != "") )
177 remoteArgs.append("--password-file=" + ( Operation[currentOperation] -> GetRemotePassword()) );
178 if ( Operation[currentOperation] -> GetRemoteSSH())
179 {
180 QString sshOptions=(Operation[currentOperation] -> GetRemoteSSHOptions()).replace("\"","\\\"")+" -o \"StrictHostKeyChecking no\" -o \"PasswordAuthentication no\" ";
181 if (WINrunning)
182 {
183 if (
184 Operation[currentOperation] -> GetRemoteSSHPassword() != "")
185 if ( Operation[currentOperation] -> GetRemoteSSHPort() != 0)
186 remoteArgs.append("-e \""+Operation[currentOperation] -> GetSshCommand()+"\" "+sshOptions+" -i \"" + Operation[currentOperation] -> GetRemoteSSHPassword() + "\" -p " +
187 countStr.setNum( Operation[currentOperation] -> GetRemoteSSHPort()) );
188 else
189 remoteArgs.append("-e \""+Operation[currentOperation] -> GetSshCommand()+"\" "+sshOptions+" -i \"" + Operation[currentOperation] -> GetRemoteSSHPassword() + "\"");
190 else
191 if ( Operation[currentOperation] -> GetRemoteSSHPort() != 0)
192 remoteArgs.append("-e \""+Operation[currentOperation] -> GetSshCommand()+"\" "+sshOptions+" -p " + countStr.setNum( Operation[currentOperation] -> GetRemoteSSHPort()) );
193 else
194 remoteArgs.append("-e \""+Operation[currentOperation] -> GetSshCommand()+"\" "+sshOptions+"");
195 }
196 else
197 {
198 if ( Operation[currentOperation] -> GetRemoteSSHPassword() != "")
199 if ( Operation[currentOperation] -> GetRemoteSSHPort() != 0)
200 remoteArgs.append("-e "+sshCommandPath+" -i " + Operation[currentOperation] -> GetRemoteSSHPassword() +" -p " +
201 countStr.setNum( Operation[currentOperation] -> GetRemoteSSHPort()) );
202 else
203 remoteArgs.append("-e "+sshCommandPath+" -i " + Operation[currentOperation] -> GetRemoteSSHPassword());
204 else
205 if ( Operation[currentOperation] -> GetRemoteSSHPort() != 0)
206 remoteArgs.append("-e "+sshCommandPath+" -p " + countStr.setNum( Operation[currentOperation] -> GetRemoteSSHPort()) );
207 else
208 remoteArgs.append("-e "+sshCommandPath);
209 }
210 }
211 }
212
213 //update the last execution time + logfile actions ~~~~~~~~~~~~~~~~~~~~~
214 if (!DryRun)
215 {
216 int maxSnaps = Operation[currentOperation] -> GetKeepSnapshots(); // this is the number of snapshots to keep
217 if (maxSnaps < 1)
218 maxSnaps = 1;
219 int currentSnaps = Operation[currentOperation] -> GetSnapshotsListSize(); // this is the current number of snapshots
220 if (currentSnaps < 1)
221 currentSnaps = 1;
222
223 // Juan's patch ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224 // this is just to create the .snapDefaultDir if it does not to exist so as to copy profile data later...
225
226 //we will create the snapshots default directory by using an rsync command with an empty source without --delete option
227 QProcess *mkdirProcess; mkdirProcess = new QProcess;
228 QStringList mkdirArgs; mkdirArgs.clear();
229
230 //if (WINrunning && RemoteDestUsed)
231 // mkdirArgs << "--mkdir";
232 //else
233 mkdirArgs << "--progress" << "-r";
234 //add all remote arguments exactly as used at normal backup
235 if (RemoteDestUsed)
236 mkdirArgs << remoteArgs;
237
238 // Add the destination folder
239 mkdirArgs.append(snapEmptyDir);
240 mkdirArgs.append(tempDestinationOrig);
241 if (WINrunning)
242 {
243 //bool createWinRsyncCommand(tempDirPath,QFile command1,QFile command2,bool vss,QString rsyncArgs,QString source,QString dest);
244 command2=createWinRsyncCommand(Operation[currentOperation] -> GetTempPath(),false,mkdirArgs,false);
245 if (command2=="")
246 cout << "\nfailed to create bat file in mkdirProccess";
247 else
248 mkdirProcess -> start (command2);
249 }
250 else
251 mkdirProcess -> start (command,mkdirArgs);
252 mkdirProcess -> waitForFinished();
253
254 if ((mkdirProcess -> exitCode()) == 0)
255 cout << "\n!";
256 else
257 cout << "\n!mkdir error!";
258
259 // Add the destination folder [ + sourceLast +SLASH ]
260 mkdirArgs.removeLast();
261 mkdirArgs.append(tempDestinationOrig2);
262 if (WINrunning)
263 {
264 //bool createWinRsyncCommand(tempDirPath,QFile command1,QFile command2,bool vss,QString rsyncArgs,QString source,QString dest);
265 command2=createWinRsyncCommand(Operation[currentOperation] -> GetTempPath(),false,mkdirArgs,false);
266 if (command2=="")
267 cout << "\nfailed to create bat file in mkdirProccess";
268 else
269 mkdirProcess -> start (command2);
270 }
271 else
272 mkdirProcess -> start (command,mkdirArgs);
273 mkdirProcess -> waitForFinished();
274
275 if ((mkdirProcess -> exitCode()) == 0)
276 cout << "\n!";
277 else
278 cout << "\n!mkdir error!";
279
280 // Add the destination folder [ + sourceLast +SLASH ] + snapDefaultDir
281 mkdirArgs.removeLast();
282 mkdirArgs.append(tempDestination);
283 // QTemporaryFile command1(QDir::tempPath()+"\\qt_tempXXXXXX.bat");
284 // QTemporaryFile command2(QDir::tempPath()+"\\qt_tempXXXXXX.bat");
285 if (WINrunning)
286 {
287 //bool createWinRsyncCommand(tempDirPath,QFile command1,QFile command2,bool vss,QString rsyncArgs,QString source,QString dest);
288 command2=createWinRsyncCommand(Operation[currentOperation] -> GetTempPath(),false,mkdirArgs,false);
289 if (command2=="")
290 cout << "\nfailed to create bat file in rmProccess";
291 else
292 mkdirProcess -> start (command2);
293 }
294 else
295 mkdirProcess -> start (command,mkdirArgs);
296 mkdirProcess -> waitForFinished();
297
298 if ((mkdirProcess -> exitCode()) == 0)
299 cout << "\n!";
300 else
301 cout << "\n!mkdir error!";
302 // Juan's patch END~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
303
304 // first remove the older logfiles and snapshots if max keep snapshots is reached
305 if (currentSnaps >= maxSnaps)
306 {
307 cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
308 cout << " Removing old snapshots and logfiles of task: " <<
309 QString((Operation[currentOperation] -> GetName()).toUtf8()).toStdString() << "\n";
310
311 // ************** actually REMOVE DATA of all older snapshots ***************************
312 // ******************************************************************************
313
314
315 // increase the remove limit to include the source.size() if "backup dir by name" is used
316 if (Operation[currentOperation] -> GetTypeDirName())
317 removeCharLimit = 4 + sourceLast.size()+1;
318 else
319 removeCharLimit = 4;
320
321 QProcess *rmProcess; rmProcess = new QProcess;
322 QStringList rmArgs;
323 rmArgs << "--progress" << "-r" << "--delete-after";
324 int snapToKeep = currentSnaps-maxSnaps + 1;
325 while ( snapToKeep < currentSnaps )
326 {
327 if (WINrunning)
328 rmArgs.append("--filter=protect " + Operation[currentOperation] -> GetSnapshotsListItem(snapToKeep) + XnixSLASH);
329 else
330 rmArgs.append("--filter=protect " + Operation[currentOperation] -> GetSnapshotsListItem(snapToKeep) + SLASH);
331 snapToKeep++;
332 }
333 // protect the backup profile dir too
334 if (WINrunning)
335 rmArgs.append("--filter=protect " + profileName + ".profile" + XnixSLASH);
336 else
337 rmArgs.append("--filter=protect " + profileName + ".profile" + SLASH);
338
339 //also add all remote arguments exactly as used at normal backup
340 if (RemoteDestUsed)
341 rmArgs << remoteArgs;
342
343 rmArgs.append(snapEmptyDir);
344 rmArgs.append(tempDestination);
345 if (WINrunning)
346 {
347 //bool createWinRsyncCommand(tempDirPath,QFile command1,QFile command2,bool vss,QString rsyncArgs,QString source,QString dest);
348 command2=createWinRsyncCommand(Operation[currentOperation] -> GetTempPath(),false,rmArgs,false);
349 if (command2=="")
350 cout << "\nfailed to create bat file in rmProccess";
351 else
352 {
353 rmProcess -> start (command2);
354 rmProcess -> waitForFinished();
355 }
356 }
357 else
358 {
359 rmProcess -> start (command,rmArgs);
360 rmProcess -> waitForFinished();
361 }
362
363 if ((rmProcess -> exitCode()) == 0)
364 cout << "\nRemoved all older snapshots data";// << QString((tempDestination + Operation[currentOperation] -> GetSnapshotsListItem(0) + SLASH).toUtf8()).toStdString();
365 else
366 cout << "\nfailed to remove all older snapshots data";// << QString((tempDestination + Operation[currentOperation] -> GetSnapshotsListItem(0) + SLASH).toUtf8()).toStdString() << "\n";
367 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
368
369 count = 0;
370 while ( count < (currentSnaps -maxSnaps + 1 ) )
371 {
372 //remove the changes file
373 snapchangesfilename = snapChangesDir + QString(profileName.toUtf8()) + "-" +
374 QString((Operation[currentOperation] -> GetName()).toUtf8()) + "-" +
375 (Operation[currentOperation] -> GetSnapshotsListItem(0)) + ".changes.log";
376 snapfile.setFileName(snapchangesfilename);
377 if (snapfile.exists())
378 {
379 if (snapfile.remove()) // this is the old snapshot changes file
380 cout << "\nRemoving " << QString(snapchangesfilename.toUtf8()).toStdString();
381 else
382 cout << "\nfailed to remove " << QString(snapchangesfilename.toUtf8()).toStdString() << "\n";
383 }
384
385 //remove the oldest logfile
386 logfilename = logDir + QString(profileName.toUtf8()) + "-" +
387 QString((Operation[currentOperation] -> GetName()).toUtf8()) + "-" +
388 Operation[currentOperation] -> GetSnapshotsListItem(0) + ".log";
389 logfile.setFileName(logfilename); // this is the old logfile
390 if (logfile.exists())
391 {
392 if (logfile.remove())
393 cout << "\nRemoving " << QString(logfilename.toUtf8()).toStdString();
394 else
395 cout << "\nfailed to remove " << QString(logfilename.toUtf8()).toStdString() << "\n";
396 }
397
398 //remove the oldest snapshot (0) from the list
399 Operation[currentOperation] -> RemoveSnapshotsListItem (0);
400 count++;
401 }
402 }
403 // the following is transfered in the very beginning of the actions for !DryRun,
404 /*else // this is just to create the .snapDefaultDir if it does not to exist so as to copy profile data later...
405 {
406 //we will create the snapshots default directory by using an rsync command with an empty source without --delete option
407 QProcess *mkdirProcess; mkdirProcess = new QProcess;
408 QStringList mkdirArgs; mkdirArgs.clear();
409 if ( (WINrunning) && (RemoteDestUsed) )
410 mkdirArgs << "--mkdir";
411 else
412 mkdirArgs << "--progress" << "-r";
413
414 //add all remote arguments exactly as used at normal backup
415 if (RemoteDestUsed)
416 mkdirArgs << remoteArgs;
417
418 mkdirArgs.append(snapEmptyDir);
419 mkdirArgs.append(tempDestination);
420 mkdirProcess -> start (command,mkdirArgs);
421 mkdirProcess -> waitForFinished();
422
423 if ((mkdirProcess -> exitCode()) == 0)
424 cout << "\n!!";
425 else
426 cout << "\n!";
427
428 }*/
429
430 //set the current date and time as the operation's last execution date-time
431 Operation[currentOperation] -> SetLastExecutionTime (QDateTime::currentDateTime());
432
433 // add a new snapshot with the last execution date-time
434 Operation[currentOperation] ->
435 AddSnapshotsListItem ((Operation[currentOperation] ->
436 GetLastExecutionTime()).toString("yyyyMMddhhmmss"));
437 currentSnaps = Operation[currentOperation] -> GetSnapshotsListSize(); // update the current number of snapshots
438
439 // set a new changes file. This has a tag of the previous snapshot will include changes made to this snapshot
440 snapchangesfilename = snapChangesDir + QString(profileName.toUtf8()) + "-" +
441 QString((Operation[currentOperation] -> GetName()).toUtf8()) + "-" +
442 (Operation[currentOperation] -> GetSnapshotsListItem(currentSnaps - 1)) + ".changes.log";
443 snapfile.setFileName(snapchangesfilename);
444
445 // set a new logfile
446 logfilename = logDir + QString(profileName.toUtf8()) + "-" +
447 QString((Operation[currentOperation] -> GetName()).toUtf8()) + "-" +
448 ( Operation[currentOperation] -> GetSnapshotsListItem(currentSnaps - 1) ) + ".log";
449
450 logfile.setFileName(logfilename); // this is the current logfile
451 if (logfile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) //create a new log file
452 {
453 writeToLog = true; //& if it's ok
454 syncProcess -> setStandardOutputFile(logfilename, QIODevice::Append );
455 syncProcess -> setStandardErrorFile(logfilename, QIODevice::Append );
456 }
457 else
458 {
459 cout << "\nError writing to log:" << QString(logfilename.toUtf8()).toStdString();
460 writeToLog = false;
461 }
462
463 // reset the error counter
464 errorCount = 0; // Number of errors from one task (max value is 1)
465 }
466
467 // The following part will be run as many times as the RepeatOnFail argument
468 // It includes execute before, task & execute after actions
469 int repeatTaskOnFailMax = Operation[currentOperation] -> GetRepeatOnFail(); // This holds the number of re-runs to try if the task fails for a reason
470 int RunTry = 0; // This run is No... RunTry
471 bool runNOW = true;
472
473 //pre-task commands execution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
474 count = 0;
475 bool StopTaskExecution = false;
476
477 while ( (Operation[currentOperation] -> GetExecuteBeforeListSize() > count) && (!StopTaskExecution) )
478 {
479 cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
480 cout << " Now executing pre-task command: "
481 << QString((Operation[currentOperation] -> GetExecuteBeforeListItem(count)).toUtf8()).toStdString() << "\n";
482
483 logFileUpdate("pre-starting","",count); //update the logfile
484
485 RunTry = 0; // This run of the command is No...
486 runNOW = true; // run it this time
487
488 while ( (RunTry < repeatTaskOnFailMax+1) && (runNOW) )
489 {
490 runNOW = false; // do NOT run this another time if it goes ok
491
492 if (RunTry > 0)
493 {
494 cout << "\n Repeating execution of pre-task command due to failure - run " << RunTry+1 << " of " << repeatTaskOnFailMax+1 << "\n\n";
495 logFileUpdate("repeat-on-fail","",count); //update the logfile
496 }
497
498 //syncProcess -> execute (Operation[currentOperation] -> GetExecuteBeforeListItem(count));
499 syncProcess -> start (Operation[currentOperation] -> GetExecuteBeforeListItem(count));
500
501 //wait for the process to start and finish
502 if (syncProcess -> waitForStarted (-1)) // the "-1" arguments are used to avoid timing out
503 {
504 cout << "\nThe process started successfully\n";
505 syncProcess -> waitForFinished (-1);
506 }
507 else
508 {
509 cout << "\nThe process failed to start\n";
510 errorCount++;
511 if (RunTry < repeatTaskOnFailMax+1)
512 runNOW = true; // run it another time because of error
513
514 if ( (Operation[currentOperation] -> GetExecuteBeforeListItemState(count) == true) && (RunTry == repeatTaskOnFailMax) )
515 {
516 StopTaskExecution = true;
517 break;
518 }
519 }
520
521 cout << "\nexit code : " << syncProcess -> exitCode();
522 cout << "\nexit status : " << syncProcess -> exitStatus() << "\n";
523 if (syncProcess -> exitCode() != 0)
524 {
525 errorCount++;
526 if (RunTry < repeatTaskOnFailMax+1)
527 runNOW = true; // run it another time because of error
528 if ( (Operation[currentOperation] -> GetExecuteBeforeListItemState(count) == true) && (RunTry == repeatTaskOnFailMax) )
529 {
530 StopTaskExecution = true;
531 break;
532 }
533 }
534 RunTry++;
535 } // Main repeat-On-Fail loop -> The specific command will be repeated according to user setting
536 logFileUpdate("pre-finished", "", count);
537 count++;
538 } // Execute before commands loop
539
540 //task execution
541 if (StopTaskExecution)
542 {
543 logFileUpdate("pre-task-exited-with-error", "", 0);
544
545 cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
546 cout << " Pre-task command exited with an error. Skipping task execution...";
547 cout << "\n--------------------------------------------------------------------------------------------\n";
548 }
549 else
550 {
551 cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
552 cout << " Now executing : " << QString((Operation[currentOperation] -> GetName()).toUtf8()).toStdString();
553 cout << "\n--------------------------------------------------------------------------------------------\n";
554
555 if (Operation[currentOperation] -> GetTypeSync())
556 logFileUpdate("rsync-starting-syncAB", "", 0);
557 else
558 logFileUpdate("rsync-starting-backup", "", 0);
559
560 // Create the destination if it does not exist
561 bool DestCreateFail = false; // This will become true if destination does not exist and cannot be created
562
563 rsyncArguments = AppendArguments(Operation[currentOperation]); //set rsync arguments
564
565 dirB = rsyncArguments[rsyncArguments.size()-1];
566 QDir destCreate (dirB.toUtf8());
567 if ( (!destCreate.exists()) && (!Operation[currentOperation] -> GetTypeSync()) && (!RemoteDestUsed) ) // local use ONLY
568 {
569 if (destCreate.mkpath(dirB.toUtf8()))
570 {
571 logFileUpdate("rsync-standard", "<br>Successfully created destination directory", 0);
572 cout << "\n\n Successfully created destination directory\n";
573 }
574 else
575 {
576 logFileUpdate("rsync-error", "<br>Failed to create destination directory", 0);
577 cout << "\n\n Failed to create destination directory\n";
578 DestCreateFail = true;
579 errorCount++;
580 }
581 }
582
583 if (!DestCreateFail)
584 {
585 //convert rsyncArguments to utf-8 for console compatibility
586 count=0;
587
588
589 while (count < rsyncArguments.size())
590 {
591 rsyncArguments[count] = QString(rsyncArguments[count].toUtf8());
592 count++;
593 }
594
595 // add the --dry-run to arguments if applicable
596 if (DryRun)
597 rsyncArguments.insert(rsyncArguments.size()-2,"--dry-run");
598 //if (writeToLog )
599 // rsyncArguments.insert(rsyncArguments.size()-2,"--log-file="+logfilename);
600
601 //syncProcess -> execute (command,rsyncArguments); // execute rsync command with rsyncArguments for backup or sync A->B
602
603 // start the repeat on fail loop for the rsync command (backup or sync1)
604 RunTry = 0; // This run of the command is No...
605 runNOW = true; // run it this time
606 while ( (RunTry < repeatTaskOnFailMax+1) && (runNOW) )
607 {
608 runNOW = false; // do NOT run this another time if it goes ok
609 if (RunTry > 0)
610 {
611 cout << "\n Repeating execution of rsync command due to failure - run " << RunTry+1 << " of " << repeatTaskOnFailMax+1 << "\n\n";
612 logFileUpdate("repeat-on-fail","",count); //update the logfile
613 }
614
615 if (WINrunning)
616 {
617 //bool createWinRsyncCommand(tempDirPath,QFile command1,QFile command2,bool vss,QString rsyncArgs,QString source,QString dest);
618 command2=createWinRsyncCommand(Operation[currentOperation] -> GetTempPath(),Operation[currentOperation]->GetOptionsVss(),rsyncArguments,false);
619 if (command2=="")
620 cout << "\nfailed to create bat file in syncProccess";
621 else
622 syncProcess -> start (command2);
623 }
624 else
625 syncProcess -> start (command,rsyncArguments);
626
627 //wait for the process to start and finish
628 if (syncProcess -> waitForStarted (-1)) // the "-1" arguments are used to avoid timing out
629 {
630 cout << "\nThe process started successfully\n";
631 syncProcess -> waitForFinished (-1);
632 }
633 else
634 {
635 cout << "\nThe process failed to start\n";
636 errorCount++;
637 }
638
639 cout << "\nrsync exit code : " << syncProcess -> exitCode();
640 cout << "\nrsync exit status : " << syncProcess -> exitStatus() << "\n";
641 if (syncProcess -> exitCode() != 0)
642 errorCount++;
643
644 /* If there is an error repeat the rsync command. Errors:
645 5 - Error starting client-server protocol
646 12 - Error in rsync protocol data stream
647 23 - Partial transfer due to error -> I took this out
648 30 - Timeout in data send/receive
649 35 - Timeout waiting for daemon connection
650 255 - unexplained error */
651 if ( (syncProcess -> exitCode()==30) || (syncProcess -> exitCode()==35) || (syncProcess -> exitCode()==255) ||
652 (syncProcess -> exitCode()==12) || (syncProcess -> exitCode()==5) )
653 runNOW = true;
654
655 RunTry++;
656 } // The repeat-on-fail loop
657 if (Operation[currentOperation] -> GetTypeSync())
658 logFileUpdate("rsync-finished-sync1", "", 0);
659 else
660 {
661 // strip unused lines from the snapshot changes file
662 QString filesAdded = "", snapLine = "";
663 if (snapfile.open(QIODevice::ReadOnly | QIODevice::Text))
664 {
665 QTextStream in(&snapfile);
666 while (!in.atEnd())
667 {
668 snapLine = in.readLine();
669 if (snapLine.contains("+++++++", Qt::CaseInsensitive))
670 {
671 snapLine = snapLine.right(snapLine.size()-snapLine.lastIndexOf("[LB]")-removeCharLimit) + "\n";
672 filesAdded.append(snapLine);
673 }
674 }
675 snapfile.close();
676 }
677 if (snapfile.open(QIODevice::WriteOnly))
678 {
679 QTextStream out(&snapfile);
680 out << filesAdded;
681 snapfile.close();
682 }
683
684 QString exportProfileDir = ""; QString sourceLast = Operation[currentOperation] -> GetSource();
685 //calculate the last folder of source
686 if (!sourceLast.endsWith(SLASH)) // this means task is of type "backup dir by name"
687 sourceLast = calculateLastPath(sourceLast); // This is the lowest dir of the source
688 else
689 sourceLast = "";
690
691 if (!rsyncArguments.isEmpty()) //rsyncArguments is calculated at executeRsync()
692 {
693 if (WINrunning && RemoteDestUsed)
694 exportProfileDir = rsyncArguments.last() + sourceLast + XnixSLASH + snapDefaultDir + profileName + ".profile" + XnixSLASH;
695 else
696 exportProfileDir = rsyncArguments.last() + sourceLast + SLASH + snapDefaultDir + profileName + ".profile" + SLASH;
697 }
698
699 // Backup profile + logs + snaps to destination
700 // If this is a backup task && not a dryrun
701 if ( (!Operation[currentOperation] -> GetTypeSync()) && (!DryRun) && (!rsyncArguments.isEmpty()) )
702 {
703 // Create the export path if it does not exist
704 QDir exportPathCreate (exportProfileDir);
705 if ( (!exportPathCreate.exists()) && (!RemoteDestUsed) ) // local use ONLY
706 exportPathCreate.mkpath(exportProfileDir);
707
708 if (exportFullProfile(exportProfileDir,"ExportOnlyTask"))
709 {
710 cout << "\n Backing-up profile, logfiles and snapshot data -> Ok\n";
711 logFileUpdate("backup-profile", " -> Ok", 0);
712 }
713 else
714 {
715 cout << "\n Backing-up profile, logfiles and snapshot data -> FAILED\n";
716 logFileUpdate("backup-profile", " -> Fail", 0);
717 }
718 }
719
720 logFileUpdate("rsync-finished", "", 0);
721 }
722
723
724 if (Operation[currentOperation] -> GetTypeSync()) //execute rsync for syncing B -> A
725 {
726 logFileUpdate("rsync-starting-syncBA", "", 0);
727 cout << "\n\n Now executing 2nd part of sync task...\n";
728
729 dirA = rsyncArguments[rsyncArguments.size()-2]; //swap last 2 arguments (dir names)
730 dirB = rsyncArguments[rsyncArguments.size()-1];
731 rsyncArguments.removeLast(); rsyncArguments.removeLast();
732 rsyncArguments.append(dirB);
733 rsyncArguments.append(dirA);
734
735 // start the repeat on fail loop for the rsync command (sync2)
736 RunTry = 0; // This run of the command is No...
737 runNOW = true; // run it this time
738 while ( (RunTry < repeatTaskOnFailMax+1) && (runNOW) )
739 {
740 runNOW = false; // do NOT run this another time if it goes ok
741 if (RunTry > 0)
742 {
743 cout << "\n Repeating execution of rsync command due to failure - run " << RunTry+1 << " of " << repeatTaskOnFailMax+1 << "\n\n";
744 logFileUpdate("repeat-on-fail","",count); //update the logfile
745 }
746
747 //syncProcess -> execute (command,rsyncArguments); // execute rsync command with rsyncArguments B->A
748 if (WINrunning)
749 {
750 //bool createWinRsyncCommand(tempDirPath,QFile command1,QFile command2,bool vss,QString rsyncArgs,QString source,QString dest);
751 command2=createWinRsyncCommand(Operation[currentOperation] -> GetTempPath(),Operation[currentOperation]->GetOptionsVss(),rsyncArguments,false);
752 if (command2=="")
753 cout << "\nfailed to create bat file in rmProccess";
754 else
755 syncProcess -> start (command2);
756 }
757 else
758 syncProcess -> start (command,rsyncArguments);
759 if (syncProcess -> waitForStarted (-1)) // the "-1" arguments are used to avoid timing out
760 {
761 cout << "\nThe process started successfully\n";
762 syncProcess -> waitForFinished (-1);
763 }
764 else
765 {
766 cout << "\nThe process failed to start\n";
767 errorCount++;
768 }
769
770 cout << "\nrsync exit code : " << syncProcess -> exitCode();
771 cout << "\nrsync exit status : " << syncProcess -> exitStatus() << "\n";
772 if (syncProcess -> exitCode() != 0)
773 errorCount++;
774
775 // If there is an error repeat the rsync command. Errors
776 if ( (syncProcess -> exitCode()==30) || (syncProcess -> exitCode()==35) || (syncProcess -> exitCode()==255) ||
777 (syncProcess -> exitCode()==12) || (syncProcess -> exitCode()==5) || (syncProcess -> exitCode()==23) )
778 runNOW = true;
779
780 RunTry++;
781 } // The repeat-on-fail loop
782 logFileUpdate("rsync-finished", "", 0);
783
784 }
785
786 //post-task commands execution
787 count = 0;
788 while ( (Operation[currentOperation] -> GetExecuteAfterListSize() > count) && (!StopTaskExecution) )
789 {
790 cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
791 cout << " Now executing post-task command: "
792 << QString(Operation[currentOperation] -> GetExecuteAfterListItem(count).toUtf8()).toStdString() << "\n";
793
794 //update the logfile
795 logFileUpdate("post-starting", "", count);
796
797 RunTry = 0; // This run of the command is No...
798 runNOW = true; // run it this time
799 while ( (RunTry < repeatTaskOnFailMax+1) && (runNOW) )
800 {
801 runNOW = false; // do NOT run this another time if it goes ok
802 if (RunTry > 0)
803 {
804 cout << "\n Repeating execution of post-rsync command due to failure - run " << RunTry+1 << " of " << repeatTaskOnFailMax+1 << "\n\n";
805 logFileUpdate("repeat-on-fail","",count); //update the logfile
806 }
807
808 //syncProcess -> execute (Operation[currentOperation] -> GetExecuteAfterListItem(count));
809
810 syncProcess -> start (Operation[currentOperation] -> GetExecuteAfterListItem(count));
811 if (syncProcess -> waitForStarted (-1)) // the "-1" arguments are used to avoid timing out
812 {
813 cout << "\nThe process started successfully\n";
814 syncProcess -> waitForFinished (-1);
815 }
816 else
817 {
818 cout << "\nThe process failed to start\n";
819 errorCount++;
820
821 if (RunTry < repeatTaskOnFailMax+1)
822 runNOW = true; // run it another time because of error
823
824 if ( (Operation[currentOperation] -> GetExecuteAfterListItemState(count) == true) && (RunTry == repeatTaskOnFailMax) )
825 {
826 StopTaskExecution = true;
827 break;
828 }
829 }
830
831 cout << "\nexit code : " << syncProcess -> exitCode();
832 cout << "\nexit status : " << syncProcess -> exitStatus() << "\n";
833 if (syncProcess -> exitCode() != 0)
834 {
835 errorCount++;
836
837 if (RunTry < repeatTaskOnFailMax+1)
838 runNOW = true; // run it another time because of error
839
840 if ( (Operation[currentOperation] -> GetExecuteAfterListItemState(count) == true) && (RunTry == repeatTaskOnFailMax) )
841 {
842 StopTaskExecution = true;
843 break;
844 }
845 }
846
847 RunTry++;
848 } // The repeat-on-fail loop
849
850 logFileUpdate("post-finished", "", count);
851
852 count++;
853 }
854
855 if (StopTaskExecution)
856 {
857 logFileUpdate("pre-task-exited-with-error", "", 0);
858
859 cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
860 cout << " Post-task command exited with an error. Skipping executing the rest of commands...";
861 cout << "\n--------------------------------------------------------------------------------------------\n";
862 }
863
864 }
865 } // Task & execute after task loop
866
867
868
869 // close the logfile
870 if (writeToLog){
871 QTextStream out(&logfile);
872 out << "<pre>";
873 logfile.close();
874 }
875
876 // Update the last execution errors and .changes file if real run
877 if (!DryRun)
878 Operation[currentOperation] -> SetLastExecutionErrors (errorCount); // update the last execution errors
879
880 errorsFound = errorsFound + errorCount;
881 errorCount = 0;
882 }
883 currentOperation++;
884 }
885 }
886
887
888 // thats_all===================================================================================================================
889 // Displays an "all done" message
890 void commandline::thats_all()
891 {
892 cout << "============================================================================================\n";
893 cout << " " << QDateTime::currentDateTime().toString(Qt::SystemLocaleLongDate).toStdString() << "\n";
894 cout << " Syncing and backing up is finished";
895 if (DryRun)
896 cout << " (simulation mode)";
897 if (errorsFound == 0)
898 cout << "\n No errors found";
899 else
900 cout << "\n errors found: " << countStr.setNum(errorsFound).toStdString();
901 if (writeToLog)
902 cout << "\n logfile(s) have been created under directory: " << logDir.toStdString();
903 cout << "\n\n hope everything went ok ;-)\n";
904 cout << "============================================================================================\n";
905
906 saveProfile(QString(currentProfile.toUtf8())); // updates the execution time
907
908 // send an email
909 if ( (!emailNever) && (!DryRun) )
910 {
911 bool send = true;
912 if ( ((emailError) && (errorsFound == 0)) // do not send if the condition "error" is checked and there are no errors
913 ||
914 ((emailSchedule) && (!NoQuestions)) ) // do not send if the condition "scheduled" is checked
915 // & --no-questions is NOT given as argument
916 send = false;
917
918 // ***** gui mode and "schedule" is covered in executenow.cpp ******
919
920 if (send)
921 {
922 cout << "\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
923 cout << "trying to send an email\n";
924 cout << " . . .\n\n";
925 cout << sendEmailNow(false).toStdString();
926 }
927 }
928 }
929
930
931 // end of commandline.cpp---------------------------------------------------------
932