forked from deajan/osync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
osync.sh
executable file
·2209 lines (1968 loc) · 70.9 KB
/
osync.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
PROGRAM="Osync" # Rsync based two way sync engine with fault tolerance
AUTHOR="(L) 2013-2015 by Orsiris \"Ozy\" de Jong"
CONTACT="http://www.netpower.fr/osync - ozy@netpower.fr"
PROGRAM_VERSION=1.1-dev
PROGRAM_BUILD=2015090903
## type doesn't work on platforms other than linux (bash). If if doesn't work, always assume output is not a zero exitcode
if ! type -p "$BASH" > /dev/null; then
echo "Please run this script only with bash shell. Tested on bash >= 3.2"
exit 127
fi
## allow debugging from command line with preceding ocsync with DEBUG=yes
if [ ! "$DEBUG" == "yes" ]; then
DEBUG=no
SLEEP_TIME=.1
else
SLEEP_TIME=3
fi
SCRIPT_PID=$$
LOCAL_USER=$(whoami)
LOCAL_HOST=$(hostname)
## Default log file until config file is loaded
if [ -w /var/log ]; then
LOG_FILE=/var/log/osync.log
else
LOG_FILE=./osync.log
fi
## Default directory where to store temporary run files
if [ -w /tmp ]; then
RUN_DIR=/tmp
elif [ -w /var/tmp ]; then
RUN_DIR=/var/tmp
else
RUN_DIR=.
fi
## Working directory. Will keep current file states, backups and soft deleted files.
OSYNC_DIR=".osync_workdir"
## Log a state message every $KEEP_LOGGING seconds. Should not be equal to soft or hard execution time so your log won't be unnecessary big.
KEEP_LOGGING=1801
## Correct output of sort command (language agnostic sorting)
export LC_ALL=C
ALERT_LOG_FILE=$RUN_DIR/osync_lastlog
function Dummy {
sleep .1
}
function _logger {
local value="${1}" # What to log
echo -e "$value" >> "$LOG_FILE"
if [ $silent -eq 0 ]; then
echo -e "$value"
fi
}
function Logger {
local value="${1}" # What to log
local level="${2}" # Log level: DEBUG, NOTICE, WARN, ERROR, CRITIAL
# Special case in daemon mode we should timestamp instead of counting seconds
if [ $sync_on_changes -eq 1 ]; then
prefix="$(date) - "
else
prefix="TIME: $SECONDS - "
fi
if [ "$level" == "CRITICAL" ]; then
_logger "$prefix\e[41m$value\e[0m"
ERROR_ALERT=1
elif [ "$level" == "ERROR" ]; then
_logger "$prefix\e[91m$value\e[0m"
ERROR_ALERT=1
elif [ "$level" == "WARN" ]; then
_logger "$prefix\e[93m$value\e[0m"
elif [ "$level" == "NOTICE" ]; then
_logger "$prefix$value"
elif [ "$level" == "DEBUG" ]; then
if [ "$DEBUG" == "yes" ]; then
_logger "$prefix$value"
fi
else
_logger "\e[41mLogger function called without proper loglevel.\e[0m"
_logger "$prefix$value"
fi
}
function TrapError {
local job="$0"
local line="$1"
local code="${2:-1}"
if [ $silent -eq 0 ]; then
echo -e " /!\ ERROR in ${job}: Near line ${line}, exit code ${code}"
fi
}
function TrapStop {
if [ $soft_stop -eq 0 ]; then
Logger " /!\ WARNING: Manual exit of osync is really not recommended. Sync will be in inconsistent state." "WARN"
Logger " /!\ WARNING: If you are sure, please hit CTRL+C another time to quit." "WARN"
soft_stop=1
return 1
fi
if [ $soft_stop -eq 1 ]; then
Logger " /!\ WARNING: CTRL+C hit twice. Quitting osync. Please wait..." "WARN"
soft_stop=2
exit 1
fi
}
function TrapQuit {
if [ $error_alert -ne 0 ]; then
if [ "$DEBUG" != "yes" ]; then
SendAlert
else
Logger "Debug mode, no alert mail will be sent." "NOTICE"
fi
UnlockDirectories
CleanUp
Logger "Osync finished with errors." "WARN"
exitcode=1
else
UnlockDirectories
CleanUp
Logger "Osync finished." "NOTICE"
exitcode=0
fi
if ps -p $child_pid > /dev/null 2>&1
then
kill -9 $child_pid
fi
if ps -p $sub_pid > /dev/null 2>&1
then
kill -9 $sub_pid
fi
exit $exitcode
}
function Spinner {
if [ $silent -eq 1 ]; then
return 0
fi
case $toggle
in
1)
echo -n " \ "
echo -ne "\r"
toggle="2"
;;
2)
echo -n " | "
echo -ne "\r"
toggle="3"
;;
3)
echo -n " / "
echo -ne "\r"
toggle="4"
;;
*)
echo -n " - "
echo -ne "\r"
toggle="1"
;;
esac
}
function EscapeSpaces {
local string="${1}" # String on which space will be escaped
echo $(echo "$string" | sed 's/ /\\ /g')
}
function CleanUp {
if [ "$DEBUG" != "yes" ]; then
rm -f $RUN_DIR/osync_*_$SCRIPT_PID
fi
}
function SendAlert {
if [ "$quick_sync" == "2" ]; then
Logger "Current task is a quicksync task. Will not send any alert." "NOTICE"
return 0
fi
eval "cat \"$LOG_FILE\" $COMPRESSION_PROGRAM > $ALERT_LOG_FILE"
MAIL_ALERT_MSG=$MAIL_ALERT_MSG$'\n\n'$(tail -n 25 "$LOG_FILE")
if type -p mutt > /dev/null 2>&1
then
echo $MAIL_ALERT_MSG | $(type -p mutt) -x -s "Sync alert for $SYNC_ID" $DESTINATION_MAILS -a "$ALERT_LOG_FILE"
if [ $? != 0 ]; then
Logger "WARNING: Cannot send alert email via $(type -p mutt) !!!" "WARN"
else
Logger "Sent alert mail using mutt." "NOTICE"
fi
elif type -p mail > /dev/null 2>&1
then
echo $MAIL_ALERT_MSG | $(type -p mail) -a "$ALERT_LOG_FILE" -s "Sync alert for $SYNC_ID" $DESTINATION_MAILS
if [ $? != 0 ]; then
Logger "WARNING: Cannot send alert email via $(type -p mail) with attachments !!!" "WARN"
echo $MAIL_ALERT_MSG | $(type -p mail) -s "Sync alert for $SYNC_ID" $DESTINATION_MAILS
if [ $? != 0 ]; then
Logger "WARNING: Cannot send alert email via $(type -p mail) without attachments !!!" "WARN"
else
Logger "Sent alert mail using mail command without attachment." "NOTICE"
fi
else
Logger "Sent alert mail using mail command." "NOTICE"
fi
elif type -p sendemail > /dev/null 2>&1
then
if [ "$SMTP_USER" != "" ] && [ "$SMTP_PASSWORD" != "" ]; then
$SMTP_OPTIONS="-xu $SMTP_USER -xp $SMTP_PASSWORD"
else
$SMTP_OPTIONS=""
fi
$(type -p sendemail) -f $SENDER_MAIL -t $DESTINATION_MAILS -u "Backup alert for $BACKUP_ID" -m "$MAIL_ALERT_MSG" -s $SMTP_SERVER $SMTP_OPTIONS > /dev/null 2>&1
if [ $? != 0 ]; then
Logger "WARNING: Cannot send alert email via $(type -p sendemail) !!!" "WARN"
else
Logger "Sent alert mail using sendemail command without attachment." "NOTICE"
fi
else
Logger "WARNING: Cannot send alert email (no mutt / mail present) !!!" "WARN"
return 1
fi
if [ -f "$ALERT_LOG_FILE" ]; then
rm "$ALERT_LOG_FILE"
fi
}
function LoadConfigFile {
local config_file="${1}"
if [ ! -f "$config_file" ]; then
Logger "Cannot load configuration file [$config_file]. Sync cannot start." "CRITICAL"
exit 1
elif [[ "$1" != *".conf" ]]; then
Logger "Wrong configuration file supplied [$config_file]. Sync cannot start." "CRITICAL"
exit 1
else
egrep '^#|^[^ ]*=[^;&]*' "$config_file" > "$RUN_DIR/osync_config_$SCRIPT_PID"
source "$RUN_DIR/osync_config_$SCRIPT_PID"
fi
}
function CheckEnvironment {
if [ "$REMOTE_SYNC" == "yes" ]; then
if ! type -p ssh > /dev/null 2>&1
then
Logger "ssh not present. Cannot start sync." "CRITICAL"
return 1
fi
fi
if ! type -p rsync > /dev/null 2>&1
then
Logger "rsync not present. Sync cannot start." "CRITICAL"
return 1
fi
}
function GetLocalOS {
LOCAL_OS_VAR=$(uname -spio 2>&1)
if [ $? != 0 ]; then
LOCAL_OS_VAR=$(uname -v 2>&1)
if [ $? != 0 ]; then
LOCAL_OS_VAR=($uname)
fi
fi
case $LOCAL_OS_VAR in
*"Linux"*)
LOCAL_OS="Linux"
;;
*"BSD"*)
LOCAL_OS="BSD"
;;
*"MINGW32"*)
LOCAL_OS="msys"
;;
*"Darwin"*)
LOCAL_OS="MacOSX"
;;
*)
Logger "Running on >> $LOCAL_OS_VAR << not supported. Please report to the author." "ERROR"
exit 1
;;
esac
Logger "Local OS: [$LOCAL_OS_VAR]." "DEBUG"
}
function GetRemoteOS {
if [ "$REMOTE_SYNC" == "yes" ]; then
CheckConnectivity3rdPartyHosts
CheckConnectivityRemoteHost
eval "$SSH_CMD \"uname -spio\" > $RUN_DIR/osync_remote_os_$SCRIPT_PID 2>&1" &
child_pid=$!
WaitForTaskCompletion $child_pid 120 240
retval=$?
if [ $retval != 0 ]; then
eval "$SSH_CMD \"uname -v\" > $RUN_DIR/osync_remote_os_$SCRIPT_PID 2>&1" &
child_pid=$!
WaitForTaskCompletion $child_pid 120 240
retval=$?
if [ $retval != 0 ]; then
eval "$SSH_CMD \"uname\" > $RUN_DIR/osync_remote_os_$SCRIPT_PID 2>&1" &
child_pid=$!
WaitForTaskCompletion $child_pid 120 240
retval=$?
if [ $retval != 0 ]; then
Logger "Cannot Get remote OS type." "ERROR"
fi
fi
fi
REMOTE_OS_VAR=$(cat $RUN_DIR/osync_remote_os_$SCRIPT_PID)
case $REMOTE_OS_VAR in
*"Linux"*)
REMOTE_OS="Linux"
;;
*"BSD"*)
REMOTE_OS="BSD"
;;
*"MINGW32"*)
REMOTE_OS="msys"
;;
*"Darwin"*)
REMOTE_OS="MacOSX"
;;
*"ssh"*|*"SSH"*)
Logger "Cannot connect to remote system." "CRITICAL"
exit 1
;;
*)
Logger "Running on remote OS failed. Please report to the author if the OS is not supported." "CRITICAL"
Logger "Remote OS said:\n$REMOTE_OS_VAR" "CRITICAL"
exit 1
esac
Logger "Remote OS: [$REMOTE_OS_VAR]." "DEBUG"
fi
}
function WaitForTaskCompletion {
local pid="${1}" # pid to wait for
local soft_max_time="${2}" # If program with pid $pid takes longer than $soft_max_time seconds, will log a warning, unless $soft_max_time equals 0.
local hard_max_time="${3}" # If program with pid $pid takes longer than $hard_max_time seconds, will stop execution, unless $hard_max_time equals 0.
__CheckArguments 3 $# $FUNCNAME "$*"
local soft_alert=0 # Does a soft alert need to be triggered
local log_ttime=0 # local time instance for comparaison
local seconds_begin=$SECONDS # Seconds since the beginning of the script
local exec_time=0 # Seconds since the beginning of this function
while eval "$PROCESS_TEST_CMD" > /dev/null
do
Spinner
exec_time=$(($SECONDS - $seconds_begin))
if [ $((($exec_time + 1) % $KEEP_LOGGING)) -eq 0 ]; then
if [ $log_ttime -ne $exec_time ]; then
log_ttime=$exec_time
Logger "Current task still running." "NOTICE"
fi
fi
if [ $exec_time -gt $soft_max_time ]; then
if [ $soft_alert -eq 0 ] && [ $soft_max_time -ne 0 ]; then
Logger "Max soft execution time exceeded for task." "WARN"
soft_alert=1
fi
if [ $exec_time -gt $hard_max_time ] && [ $hard_max_time -ne 0 ]; then
Logger "Max hard execution time exceeded for task. Stopping task execution." "ERROR"
kill -s SIGTERM $pid
if [ $? == 0 ]; then
Logger "Task stopped succesfully" "NOTICE"
else
Logger "Sending SIGTERM to proces failed. Trying the hard way." "ERROR"
kill -9 $pid
if [ $? != 0 ]; then
Logger "Could not stop task." "ERROR"
fi
fi
return 1
fi
fi
sleep $SLEEP_TIME
done
wait $pid
return $?
}
function WaitForCompletion {
local pid="${1}" # pid to wait for
local soft_max_time="${2}" # If program with pid $pid takes longer than $soft_max_time seconds, will log a warning, unless $soft_max_time equals 0.
local hard_max_time="${3}" # If program with pid $pid takes longer than $hard_max_time seconds, will stop execution, unless $hard_max_time equals 0.
__CheckArguments 3 $# $FUNCNAME "$*"
local soft_alert=0 # Does a soft alert need to be triggered
local log_ttime=0 # local time instance for comparaison
local seconds_begin=$SECONDS # Seconds since the beginning of the script
local exec_time=0 # Seconds since the beginning of this function
while eval "$PROCESS_TEST_CMD" > /dev/null
do
Spinner
if [ $((($SECONDS + 1) % $KEEP_LOGGING)) -eq 0 ]; then
if [ $log_time -ne $SECONDS ]; then
log_time=$SECONDS
Logger "Current task still running." "NOTICE"
fi
fi
if [ $SECONDS -gt $soft_max_time ]; then
if [ $soft_alert -eq 0 ] && [ $soft_max_time != 0 ]; then
Logger "Max soft execution time exceeded for script." "WARN"
soft_alert=1
fi
if [ $SECONDS -gt $hard_max_time ] && [ $hard_max_time != 0 ]; then
Logger "Max hard execution time exceeded for script. Stopping current task execution." "ERROR"
kill -s SIGTERM $pid
if [ $? == 0 ]; then
Logger "Task stopped succesfully" "NOTICE"
else
Logger "Sending SIGTERM to proces failed. Trying the hard way." "ERROR"
kill -9 $pid
if [ $? != 0 ]; then
Logger "Could not stop task." "ERROR"
fi
fi
return 1
fi
fi
sleep $SLEEP_TIME
done
wait $pid
return $?
}
function RunLocalCommand {
local command="${1}" # Command to run
local hard_max_time="${2}" # Max time to wait for command to compleet
__CheckArguments 2 $# $FUNCNAME "$*"
if [ $dryrun -ne 0 ]; then
Logger "Dryrun: Local command [$command] not run." "NOTICE"
return 1
fi
Logger "Running command [$command] on local host." "NOTICE"
eval "$command" > $RUN_DIR/osync_run_local_$SCRIPT_PID 2>&1 &
child_pid=$!
WaitForTaskCompletion $child_pid 0 $hard_max_time
retval=$?
if [ $retval -eq 0 ]; then
Logger "Command succeded." "NOTICE"
else
Logger "Command failed." "ERROR"
fi
if [ $verbose -eq 1 ] || [ $retval -ne 0 ]; then
Logger "Command output:\n$(cat $RUN_DIR/osync_run_local_$SCRIPT_PID)" "NOTICE"
fi
if [ "$STOP_ON_CMD_ERROR" == "yes" ] && [ $retval -ne 0 ]; then
Logger "Stopping on command execution error." "CRITICAL"
exit 1
fi
}
## Runs remote command $1 and waits for completition in $2 seconds
function RunRemoteCommand {
local command="${1}" # Command to run
local hard_max_time="${2}" # Max time to wait for command to compleet
__CheckArguments 2 $# $FUNCNAME "$*"
CheckConnectivity3rdPartyHosts
CheckConnectivityRemoteHost
if [ $dryrun -ne 0 ]; then
Logger "Dryrun: Local command [$command] not run." "NOTICE"
return 1
fi
Logger "Running command [$command] on remote host." "NOTICE"
eval "$SSH_CMD \"$command\" > $RUN_DIR/osync_run_remote_$SCRIPT_PID 2>&1 &"
child_pid=$!
WaitForTaskCompletion $child_pid 0 $hard_max_time
retval=$?
if [ $retval -eq 0 ]; then
Logger "Command succeded." "NOTICE"
else
Logger "Command failed." "ERROR"
fi
if [ -f $RUN_DIR/osync_run_remote_$SCRIPT_PID ] && ([ $verbose -eq 1 ] || [ $retval -ne 0 ])
then
Logger "Command output:\n$(cat $RUN_DIR/osync_run_remote_$SCRIPT_PID)" "NOTICE"
fi
if [ "$STOP_ON_CMD_ERROR" == "yes" ] && [ $retval -ne 0 ]; then
Logger "Stopping on command execution error." "CRITICAL"
exit 1
fi
}
function RunBeforeHook {
if [ "$LOCAL_RUN_BEFORE_CMD" != "" ]; then
RunLocalCommand "$LOCAL_RUN_BEFORE_CMD" $MAX_EXEC_TIME_PER_CMD_BEFORE
fi
if [ "$REMOTE_RUN_BEFORE_CMD" != "" ]; then
RunRemoteCommand "$REMOTE_RUN_BEFORE_CMD" $MAX_EXEC_TIME_PER_CMD_BEFORE
fi
}
function RunAfterHook {
if [ "$LOCAL_RUN_AFTER_CMD" != "" ]; then
RunLocalCommand "$LOCAL_RUN_AFTER_CMD" $MAX_EXEC_TIME_PER_CMD_AFTER
fi
if [ "$REMOTE_RUN_AFTER_CMD" != "" ]; then
RunRemoteCommand "$REMOTE_RUN_AFTER_CMD" $MAX_EXEC_TIME_PER_CMD_AFTER
fi
}
function CheckConnectivityRemoteHost {
if [ "$REMOTE_HOST_PING" != "no" ] && [ "$REMOTE_SYNC" != "no" ]; then
eval "$PING_CMD $REMOTE_HOST > /dev/null 2>&1"
if [ $? != 0 ]; then
Logger "Cannot ping $REMOTE_HOST" "CRITICAL"
exit 1
fi
fi
}
function CheckConnectivity3rdPartyHosts {
if [ "$REMOTE_3RD_PARTY_HOSTS" != "" ]; then
remote_3rd_party_success=0
OLD_IFS=$IFS
IFS=$' \t\n'
for i in $REMOTE_3RD_PARTY_HOSTS
do
eval "$PING_CMD $i > /dev/null 2>&1"
if [ $? != 0 ]; then
Logger "Cannot ping 3rd party host $i" "WARN"
else
remote_3rd_party_success=1
fi
done
IFS=$OLD_IFS
if [ $remote_3rd_party_success -ne 1 ]; then
Logger "No remote 3rd party host responded to ping. No internet ?" "CRITICAL"
exit 1
fi
fi
}
function __CheckArguments {
# Checks the number of arguments and raises an error if some are missing
if [ "$DEBUG" == "yes" ]; then
local number_of_arguments="${1}" # Number of arguments a function should have
local number_of_given_arguments="${2}" # Number of arguments that have been passed
local function_name="${3}" # Function name that called __CheckArguments
local arguments="${4}" # All other arguments
if [ $number_of_arguments -ne $number_of_given_arguments ]; then
Logger "Inconsistnent number of arguments in $function_name. Should have $number_of_arguments arguments, has $number_of_given_arguments arguments, see log file." "CRITICAL"
# Cannot user Logger here because $@ is a list of arguments
echo "Argumnt list: $4" >> "$LOG_FILE"
fi
if [ "$PARANOIA_DEBUG" == "yes" ]; then
# Paranoia check... Can help finding empty arguments
local count=-3 # Number of arguments minus the function calls for __CheckArguments
for i in $@; do
count=$((count + 1))
done
if [ $count -ne $1 ]; then
Logger "Function $function_name may have inconsistent number of arguments. Expected: $number_of_arguments, count: $count, see log file." "WARN"
echo "Argument list (including checks): $@" >> "$LOG_FILE"
fi
fi
fi
}
############################################################################################
### realpath.sh implementation from https://github.com/mkropat/sh-realpath
realpath() {
canonicalize_path "$(resolve_symlinks "$1")"
}
resolve_symlinks() {
_resolve_symlinks "$1"
}
_resolve_symlinks() {
_assert_no_path_cycles "$@" || return
local dir_context path
path=$(readlink -- "$1")
if [ $? -eq 0 ]; then
dir_context=$(dirname -- "$1")
_resolve_symlinks "$(_prepend_dir_context_if_necessary "$dir_context" "$path")" "$@"
else
printf '%s\n' "$1"
fi
}
_prepend_dir_context_if_necessary() {
if [ "$1" = . ]; then
printf '%s\n' "$2"
else
_prepend_path_if_relative "$1" "$2"
fi
}
_prepend_path_if_relative() {
case "$2" in
/* ) printf '%s\n' "$2" ;;
* ) printf '%s\n' "$1/$2" ;;
esac
}
_assert_no_path_cycles() {
local target path
target=$1
shift
for path in "$@"; do
if [ "$path" = "$target" ]; then
return 1
fi
done
}
canonicalize_path() {
if [ -d "$1" ]; then
_canonicalize_dir_path "$1"
else
_canonicalize_file_path "$1"
fi
}
_canonicalize_dir_path() {
(cd "$1" 2>/dev/null && pwd -P)
}
_canonicalize_file_path() {
local dir file
dir=$(dirname -- "$1")
file=$(basename -- "$1")
(cd "$dir" 2>/dev/null && printf '%s/%s\n' "$(pwd -P)" "$file")
}
# Optionally, you may also want to include:
### readlink emulation ###
readlink() {
if _has_command readlink; then
_system_readlink "$@"
else
_emulated_readlink "$@"
fi
}
_has_command() {
hash -- "$1" 2>/dev/null
}
_system_readlink() {
command readlink "$@"
}
_emulated_readlink() {
if [ "$1" = -- ]; then
shift
fi
_gnu_stat_readlink "$@" || _bsd_stat_readlink "$@"
}
_gnu_stat_readlink() {
local output
output=$(stat -c %N -- "$1" 2>/dev/null) &&
printf '%s\n' "$output" |
sed "s/^‘[^’]*’ -> ‘\(.*\)’/\1/
s/^'[^']*' -> '\(.*\)'/\1/"
# FIXME: handle newlines
}
_bsd_stat_readlink() {
stat -f %Y -- "$1" 2>/dev/null
}
#### Osync specific functions (non shared)
function CreateOsyncDirs {
if ! [ -d "$MASTER_STATE_DIR" ]; then
mkdir -p "$MASTER_STATE_DIR"
if [ $? != 0 ]; then
Logger "Cannot create master replica state dir [$MASTER_STATE_DIR]." "CRITICAL"
exit 1
fi
fi
if [ "$REMOTE_SYNC" == "yes" ]; then
CheckConnectivity3rdPartyHosts
CheckConnectivityRemoteHost
eval "$SSH_CMD \"if ! [ -d \\\"$SLAVE_STATE_DIR\\\" ]; then $COMMAND_SUDO mkdir -p \\\"$SLAVE_STATE_DIR\\\"; fi 2>&1\"" &
child_pid=$!
WaitForTaskCompletion $child_pid 0 1800
else
if ! [ -d "$SLAVE_STATE_DIR" ]; then
mkdir -p "$SLAVE_STATE_DIR" > $RUN_DIR/osync_createosyncdirs_$SCRIPT_PID 2>&1
fi
fi
if [ $? != 0 ]; then
Logger "Cannot create slave replica state dir [$SLAVE_STATE_DIR]." "CRITICAL"
Logger "Command output:\n$(cat $RUN_DIR/osync_createosyncdirs_$SCRIPT_PID)" "NOTICE"
exit 1
fi
}
function CheckMasterSlaveDirs {
#MASTER_SYNC_DIR_CANN=$(realpath "$MASTER_SYNC_DIR") #TODO: investigate realpath & readlink issues on MSYS and busybox here
#SLAVE_SYNC_DIR_CANN=$(realpath "$SLAVE_SYNC_DIR")
#if [ "$REMOTE_SYNC" != "yes" ]; then
# if [ "$MASTER_SYNC_DIR_CANN" == "$SLAVE_SYNC_DIR_CANN" ]; then
# Logger "Master directory [$MASTER_SYNC_DIR] can't be the same as slave directory." "CRITICAL"
# exit 1
# fi
#fi
if ! [ -d "$MASTER_SYNC_DIR" ]; then
if [ "$CREATE_DIRS" == "yes" ]; then
mkdir -p "$MASTER_SYNC_DIR" > $RUN_DIR/osync_checkmasterslavedirs_$SCRIPT_PID 2>&1
if [ $? != 0 ]; then
Logger "Cannot create master directory [$MASTER_SYNC_DIR]." "CRITICAL"
Logger "Command output:\n$(cat $RUN_DIR/osync_checkmasterslavedirs_$SCRIPT_PID)" "NOTICE"
exit 1
fi
else
Logger "Master directory [$MASTER_SYNC_DIR] does not exist." "CRITICAL"
exit 1
fi
fi
if [ "$REMOTE_SYNC" == "yes" ]; then
CheckConnectivity3rdPartyHosts
CheckConnectivityRemoteHost
if [ "$CREATE_DIRS" == "yes" ]; then
eval "$SSH_CMD \"if ! [ -d \\\"$SLAVE_SYNC_DIR\\\" ]; then $COMMAND_SUDO mkdir -p \\\"$SLAVE_SYNC_DIR\\\"; fi 2>&1"\" > $RUN_DIR/osync_checkmasterslavedirs_$SCRIPT_PID &
child_pid=$!
WaitForTaskCompletion $child_pid 0 1800
if [ $? != 0 ]; then
Logger "Cannot create slave directory [$SLAVE_SYNC_DIR]." "CRITICAL"
Logger "Command output:\n$(cat $RUN_DIR/osync_checkmasterslavedirs_$SCRIPT_PID)" "NOTICE"
exit 1
fi
else
eval "$SSH_CMD \"if ! [ -d \\\"$SLAVE_SYNC_DIR\\\" ]; then exit 1; fi"\" &
child_pid=$!
WaitForTaskCompletion $child_pid 0 1800
res=$?
if [ $res != 0 ]; then
Logger "Slave directory [$SLAVE_SYNC_DIR] does not exist." "CRITICAL"
exit 1
fi
fi
else
if [ ! -d "$SLAVE_SYNC_DIR" ]; then
if [ "$CREATE_DIRS" == "yes" ]; then
mkdir -p "$SLAVE_SYNC_DIR"
if [ $? != 0 ]; then
Logger "Cannot create slave directory [$SLAVE_SYNC_DIR]." "CRITICAL"
exit 1
else
Logger "Created slave directory [$SLAVE_SYNC_DIR]." "NOTICE"
fi
else
Logger "Slave directory [$SLAVE_SYNC_DIR] does not exist." "CRITICAL"
exit 1
fi
fi
fi
}
function CheckMinimumSpace {
Logger "Checking minimum disk space on master and slave." "NOTICE"
MASTER_SPACE=$(df -P "$MASTER_SYNC_DIR" | tail -1 | awk '{print $4}')
if [ $MASTER_SPACE -lt $MINIMUM_SPACE ]; then
Logger "There is not enough free space on master [$MASTER_SPACE KB]." "ERROR"
fi
if [ "$REMOTE_SYNC" == "yes" ]; then
CheckConnectivity3rdPartyHosts
CheckConnectivityRemoteHost
eval "$SSH_CMD \"$COMMAND_SUDO df -P \\\"$SLAVE_SYNC_DIR\\\"\"" > $RUN_DIR/osync_slave_space_$SCRIPT_PID &
child_pid=$!
WaitForTaskCompletion $child_pid 0 1800
SLAVE_SPACE=$(cat $RUN_DIR/osync_slave_space_$SCRIPT_PID | tail -1 | awk '{print $4}')
else
SLAVE_SPACE=$(df -P "$SLAVE_SYNC_DIR" | tail -1 | awk '{print $4}')
fi
if [ $SLAVE_SPACE -lt $MINIMUM_SPACE ]; then
Logger "There is not enough free space on slave [$SLAVE_SPACE KB]." "ERROR"
fi
}
function RsyncExcludePattern {
# Disable globbing so wildcards from exclusions don't get expanded
set -f
rest="$RSYNC_EXCLUDE_PATTERN"
while [ -n "$rest" ]
do
# Take the string until first occurence until $PATH_SEPARATOR_CHAR
str=${rest%%;*}
# Handle the last case
if [ "$rest" = "${rest/$PATH_SEPARATOR_CHAR/}" ]; then
rest=
else
# Cut everything before the first occurence of $PATH_SEPARATOR_CHAR
rest=${rest#*$PATH_SEPARATOR_CHAR}
fi
if [ "$RSYNC_EXCLUDE" == "" ]; then
RSYNC_EXCLUDE="--exclude=\"$str\""
else
RSYNC_EXCLUDE="$RSYNC_EXCLUDE --exclude=\"$str\""
fi
done
set +f
}
function RsyncExcludeFrom {
if [ ! "$RSYNC_EXCLUDE_FROM" == "" ]; then
## Check if the exclude list has a full path, and if not, add the config file path if there is one
if [ "$(basename $RSYNC_EXCLUDE_FROM)" == "$RSYNC_EXCLUDE_FROM" ]; then
RSYNC_EXCLUDE_FROM=$(dirname $ConfigFile)/$RSYNC_EXCLUDE_FROM
fi
if [ -e "$RSYNC_EXCLUDE_FROM" ]; then
RSYNC_EXCLUDE="$RSYNC_EXCLUDE --exclude-from=\"$RSYNC_EXCLUDE_FROM\""
fi
fi
}
function WriteLockFiles {
echo $SCRIPT_PID > "$MASTER_LOCK"
if [ $? != 0 ]; then
Logger "Could not set lock on master replica." "CRITICAL"
exit 1
else
Logger "Locked master replica." "NOTICE"
fi
if [ "$REMOTE_SYNC" == "yes" ]; then
CheckConnectivity3rdPartyHosts
CheckConnectivityRemoteHost
eval "$SSH_CMD \"echo $SCRIPT_PID@$SYNC_ID | $COMMAND_SUDO tee \\\"$SLAVE_LOCK\\\" > /dev/null \"" &
child_pid=$!
WaitForTaskCompletion $child_pid 0 1800
if [ $? != 0 ]; then
Logger "Could not set lock on remote slave replica." "CRITICAL"
exit 1
else
Logger "Locked remote slave replica." "NOTICE"
fi
else
echo "$SCRIPT_PID@$SYNC_ID" > "$SLAVE_LOCK"
if [ $? != 0 ]; then
Logger "Couuld not set lock on local slave replica." "CRITICAL"
exit 1
else
Logger "Locked local slave replica." "NOTICE"
fi
fi
}
function LockDirectories {
if [ $nolocks -eq 1 ]; then
return 0
fi
if [ $force_unlock -eq 1 ]; then
WriteLockFiles
if [ $? != 0 ]; then
exit 1
fi
fi
Logger "Checking for replica locks." "NOTICE"
if [ -f "$MASTER_LOCK" ]; then
master_lock_pid=$(cat $MASTER_LOCK)
Logger "Master lock pid present: $master_lock_pid" "DEBUG"
ps -p$master_lock_pid > /dev/null 2>&1
if [ $? != 0 ]; then
Logger "There is a dead osync lock on master. Instance $master_lock_pid no longer running. Resuming." "NOTICE"
else
Logger "There is already a local instance of osync that locks master replica. Cannot start. If your are sure this is an error, plaese kill instance $master_lock_pid of osync." "CRITICAL"
exit 1
fi
fi
if [ "$REMOTE_SYNC" == "yes" ]; then
CheckConnectivity3rdPartyHosts
CheckConnectivityRemoteHost
eval "$SSH_CMD \"if [ -f \\\"$SLAVE_LOCK\\\" ]; then cat \\\"$SLAVE_LOCK\\\"; fi\" > $RUN_DIR/osync_remote_slave_lock_$SCRIPT_PID" &
child_pid=$!
WaitForTaskCompletion $child_pid 0 1800
if [ -f $RUN_DIR/osync_remote_slave_lock_$SCRIPT_PID ]; then
slave_lock_pid=$(cat $RUN_DIR/osync_remote_slave_lock_$SCRIPT_PID | cut -d'@' -f1)
slave_lock_id=$(cat $RUN_DIR/osync_remote_slave_lock_$SCRIPT_PID | cut -d'@' -f2)
fi
else
if [ -f "$SLAVE_LOCK" ]; then
slave_lock_pid=$(cat "$SLAVE_LOCK" | cut -d'@' -f1)
slave_lock_id=$(cat "$SLAVE_LOCK" | cut -d'@' -f2)
fi
fi
if [ "$slave_lock_pid" != "" ] && [ "$slave_lock_id" != "" ]; then
Logger "Slave lock pid: $slave_lock_pid" "DEBUG"
ps -p$slave_lock_pid > /dev/null
if [ $? != 0 ]; then
if [ "$slave_lock_id" == "$SYNC_ID" ]; then
Logger "There is a dead osync lock on slave replica that corresponds to this master sync-id. Instance $slave_lock_pid no longer running. Resuming." "NOTICE"
else
if [ "$FORCE_STRANGER_LOCK_RESUME" == "yes" ]; then
Logger "WARNING: There is a dead osync lock on slave replica that does not correspond to this master sync-id. Forcing resume." "WARN"
else
Logger "There is a dead osync lock on slave replica that does not correspond to this master sync-id. Will not resume." "CRITICAL"
exit 1
fi
fi
else
Logger "There is already a local instance of osync that locks slave replica. Cannot start. If you are sure this is an error, please kill instance $slave_lock_pid of osync." "CRITICAL"
exit 1
fi
fi
WriteLockFiles
}
function UnlockDirectories {
if [ $nolocks -eq 1 ]; then
return 0
fi
if [ "$REMOTE_SYNC" == "yes" ]; then
CheckConnectivity3rdPartyHosts
CheckConnectivityRemoteHost
eval "$SSH_CMD \"if [ -f \\\"$SLAVE_LOCK\\\" ]; then $COMMAND_SUDO rm \\\"$SLAVE_LOCK\\\"; fi 2>&1\"" > $RUN_DIR/osync_UnlockDirectories_$SCRIPT_PID &
child_pid=$!
WaitForTaskCompletion $child_pid 0 1800
else
if [ -f "$SLAVE_LOCK" ]; then
rm "$SLAVE_LOCK" > $RUN_DIR/osync_UnlockDirectories_$SCRIPT_PID 2>&1
fi
fi
if [ $? != 0 ]; then
Logger "Could not unlock slave replica." "ERROR"
Logger "Command Output:\n$(cat $RUN_DIR/osync_UnlockDirectories_$SCRIPT_PID)" "NOTICE"
else
Logger "Removed slave replica lock." "NOTICE"
fi
if [ -f "$MASTER_LOCK" ]; then
rm "$MASTER_LOCK"
if [ $? != 0 ]; then
Logger "Could not unlock master replica." "ERROR"