forked from gboudreau/Greyhole
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgreyhole
executable file
·3814 lines (3430 loc) · 169 KB
/
greyhole
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/php
<?php
/*
Copyright 2009-2014 Guillaume Boudreau, Andrew Hopkinson
This file is part of Greyhole.
Greyhole is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Greyhole is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Greyhole. If not, see <http://www.gnu.org/licenses/>.
*/
require_once('includes/common.php');
require_once('includes/CLI/CommandLineHelper.php'); // Command line helper (abstract classes, command line definitions & parsing, Runners, etc.)
require_once('includes/DaemonRunner.php');
// This will parse the command line, and find commands and options.
// It will then instantiate the appropriate class (that extends AbstractRunner), and return it.
$cliHelper = new CommandLineHelper();
$runner = $cliHelper->processCommandLine();
// This will run the runner(!) i.e. what the user asked for will now be executed.
$runner->run();
// The runner has finished; let's clean up before quitting.
$runner->finish();
function get_next_tasks($incl_md5=FALSE, $update_idle=TRUE) {
$query = "SELECT id, action, share, full_path, additional_info, complete FROM tasks WHERE complete IN ('yes', 'thawed')" . (!$incl_md5 ? " AND action != 'md5'" : "") . " ORDER BY id ASC LIMIT 20";
$tasks = DB::getAll($query);
if ($tasks === FALSE && $update_idle) {
// No more complete = yes|thawed; let's look for complete = 'idle' tasks.
$query = "UPDATE tasks SET complete = 'yes' WHERE complete = 'idle'";
DB::execute($query);
$tasks = get_next_tasks($incl_md5, FALSE);
}
return $tasks;
}
function execute_next_task() {
global $sleep_before_task, $next_task, $current_task_id, $locked_files, $fix_symlinks_scanned_dirs;
if (isset($next_task)) {
$task = $next_task;
unset($GLOBALS['next_task']);
} else {
$task = FALSE;
if (!empty($next_tasks)) {
$task = array_shift($next_tasks);
}
if ($task === FALSE) {
$next_tasks = get_next_tasks(TRUE);
if (!empty($next_tasks)) {
$task = array_shift($next_tasks);
} else {
Log::setAction(ACTION_SLEEP);
Log::debug("Nothing to do... Sleeping.");
DB::repairTables();
check_md5_workers();
// Email any unsent fsck reports found in /usr/share/greyhole/
foreach (array('fsck_checksums.log', 'fsck_files.log') as $log_file) {
$log = new FSCKLogFile($log_file);
$log->emailAsRequired();
}
$log_level = Log::getLevel();
sleep($log_level == Log::DEBUG ? 10 : ($log_level == Log::TEST || $log_level == Log::PERF ? 1 : 600));
$locked_files = array();
return;
}
}
}
$current_task_id = $task->id;
# Postpone tasks in frozen directories until a --thaw command is received
if ($task->complete != 'thawed') {
$frozen_directories = Config::get(CONFIG_FROZEN_DIRECTORY);
foreach ($frozen_directories as $frozen_directory) {
if (string_starts_with("$task->share/$task->full_path", $frozen_directory)) {
Log::setAction($task->action);
Log::debug("Now working on task ID $task->id: $task->action " . clean_dir("$task->share/$task->full_path") . ($task->action == 'rename' ? " -> $task->share/$task->additional_info" : ''));
Log::debug(" This directory is frozen. Will postpone this task until it is thawed.");
postpone_task($task->id, 'frozen');
archive_task($task->id);
return;
}
}
}
if (array_contains($sleep_before_task, $task->id)) {
Log::setAction(ACTION_SLEEP);
Log::debug("Only locked files operations pending... Sleeping.");
$log_level = Log::getLevel();
sleep($log_level == Log::DEBUG ? 10 : ($log_level == Log::TEST ? 1 : 600));
$sleep_before_task = array();
$locked_files = array();
}
Log::setAction($task->action);
Log::info("Now working on task ID $task->id: $task->action " . clean_dir("$task->share/$task->full_path") . ($task->action == 'rename' ? " -> $task->share/$task->additional_info" : ''));
switch ($task->action) {
case 'balance':
Log::info("Starting available space balancing");
gh_balance();
Log::info("Available space balancing completed.");
break;
case 'fsck_file':
set_fsck_options($task);
$task->full_path = get_share_landing_zone($task->share) . '/' . $task->full_path;
$file_type = @filetype($task->full_path);
list($path, $filename) = explode_full_path($task->full_path);
FSCKLogFile::loadFSCKReport('Missing files'); // Create or load the fsck_report from disk
gh_fsck_file($path, $filename, $file_type, 'metastore', $task->share);
if (task_has_option($task, 'email')) {
// Save the report to disk to be able to email it when we're done with all fsck_file tasks
FSCKLogFile::saveFSCKReport();
}
break;
case 'md5':
gh_check_md5($task);
break;
case 'fsck':
$new_conf_md5 = get_conf_md5();
if (task_has_option($task, 'if-conf-changed')) {
// Let's check if the conf file changed since the last fsck
// Last value
$last_md5 = Settings::get('last_fsck_conf_md5');
// New value
if ($new_conf_md5 == $last_md5) {
Log::info("Skipping fsck; --if-conf-changed was specified, and the configuration file didn't change since the last fsck.");
break;
}
}
$fscked_dir = $task->share;
$where_clause = "";
$params = array();
if ($fscked_dir == '') {
$fsck_what_dir = 'All shares';
} else {
$fsck_what_dir = $fscked_dir;
$max_lz_length = 0;
foreach (SharesConfig::getShares() as $share_name => $share_options) {
if (strpos($fsck_what_dir, $share_options[CONFIG_LANDING_ZONE]) === 0 && strlen($share_options[CONFIG_LANDING_ZONE]) > $max_lz_length) {
$max_lz_length = strlen($share_options[CONFIG_LANDING_ZONE]);
$where_clause = "AND share = :share";
$params['share'] = $share_name;
}
}
}
// First, let's remove all md5 tasks that would be duplicates of the ones we'll create during this fsck
DB::execute("DELETE FROM tasks WHERE action = 'md5' $where_clause", $params);
// Second, let's make sure all fsck_file tasks marked idle get executed.
$query = "UPDATE tasks SET complete = 'yes' WHERE action = 'fsck_file' AND complete = 'idle' $where_clause";
DB::execute($query, $params);
$num_updated_rows = DB::getFirstValue("SELECT COUNT(*) AS num_updated_rows FROM tasks WHERE action = 'fsck_file' AND complete = 'yes' $where_clause", $params);
if ($num_updated_rows > 0) {
// Updated some fsck_file to complete; let's just return here, to allow them to be executed first.
Log::info("Will execute all ($num_updated_rows) pending fsck_file operations for $fsck_what_dir before running this fsck (task ID $task->id).");
return;
}
Log::info("Starting fsck for $fsck_what_dir");
initialize_fsck_report($fsck_what_dir);
clearstatcache();
if (task_has_option($task, 'checksums')) {
// Spawn md5 worker threads; those will calculate files MD5, and save the result in the DB.
// The Greyhole daemon will then read those, and check them against each other to make sure all is fine.
$checksums_thread_ids = array();
foreach (Config::storagePoolDrives() as $sp_drive) {
$checksums_thread_ids[] = spawn_thread('md5-worker', array($sp_drive));
}
Log::debug("Spawned " . count($checksums_thread_ids) . " worker threads to calculate MD5 checksums. Will now wait for results, and check them as they come in.");
}
set_fsck_options($task);
if ($fscked_dir == '') {
foreach (SharesConfig::getShares() as $share_name => $share_options) {
gh_fsck_reset_du($share_name);
gh_fsck($share_options[CONFIG_LANDING_ZONE], $share_name);
}
if (task_has_option($task, 'metastore')) {
foreach (get_metastores() as $metastore) {
foreach (SharesConfig::getShares() as $share_name => $share_options) {
gh_fsck_metastore($metastore, "/$share_name", $share_name);
}
}
}
if (task_has_option($task, 'orphaned')) {
foreach (Config::storagePoolDrives() as $sp_drive) {
if (is_greyhole_owned_drive($sp_drive)) {
foreach (SharesConfig::getShares() as $share_name => $share_options) {
gh_fsck("$sp_drive/$share_name", $share_name, $sp_drive);
}
}
}
}
} else {
$share_options = get_share_options_from_full_path($fscked_dir);
$storage_volume = FALSE;
if ($share_options === FALSE) {
// Since share_options is FALSE we didn't get a share path, maybe we got a storage volume path, let's check
$storage_volume = get_storage_volume_from_path($fscked_dir);
$share_options = get_share_options_from_storage_volume($fscked_dir, $storage_volume);
}
if ($share_options !== FALSE) {
$share = $share_options['name'];
$metastore = get_metastore_from_path($fscked_dir);
if ($storage_volume === FALSE && $metastore === FALSE) {
$fsck_type = FSCK_TYPE_SHARE;
} else if ($storage_volume !== FALSE) {
$fsck_type = FSCK_TYPE_STORAGE_POOL_DRIVE;
} else {
$fsck_type = FSCK_TYPE_METASTORE;
}
// Only calculate du stats if the user specified a folder in a share
if ($fsck_type == FSCK_TYPE_SHARE) {
$subdir = trim(str_replace($share_options[CONFIG_LANDING_ZONE], '', $fscked_dir), '/');
gh_fsck_reset_du($share, $subdir);
}
// Only kick off an fsck on the passed dir if it's not a metastore; that will be handled below.
if ($fsck_type != FSCK_TYPE_METASTORE) {
gh_fsck($fscked_dir, $share, $storage_volume);
}
if (task_has_option($task, 'metastore') !== FALSE) {
if ($fsck_type == FSCK_TYPE_METASTORE) {
// This is a metastore directory, so only kick off a metastore fsck for the indicated directory (this will not fsck the corresponding metastore path on other volumes)
$subdir = str_replace("$metastore", '', $fscked_dir);
Log::debug("Starting metastore fsck for $metastore/$subdir");
gh_fsck_metastore($metastore, $subdir, $share);
} else {
// This isn't a metastore dir so we'll check the metastore of this path on all volumes
if ($fsck_type == FSCK_TYPE_STORAGE_POOL_DRIVE) {
$subdir = str_replace($storage_volume, '', $fscked_dir);
} else {
$subdir = "/$share" . str_replace($share_options[CONFIG_LANDING_ZONE], '', $fscked_dir);
}
Log::debug("Starting metastores fsck for $subdir");
foreach (get_metastores() as $metastore) {
gh_fsck_metastore($metastore, $subdir, $share);
}
}
}
if ($fsck_type != FSCK_TYPE_STORAGE_POOL_DRIVE && task_has_option($task, 'orphaned')) {
$subdir = "/$share" . str_replace($share_options[CONFIG_LANDING_ZONE], '', $fscked_dir);
Log::debug("Starting orphans search for $subdir");
foreach (Config::storagePoolDrives() as $sp_drive) {
if (is_greyhole_owned_drive($sp_drive)) {
gh_fsck("$sp_drive/$subdir", $share, $sp_drive);
}
}
}
}
}
Log::info("fsck for " . ($fscked_dir == '' ? 'All shares' : $fscked_dir) . " completed.");
Settings::set('last_fsck_conf_md5', $new_conf_md5);
if (task_has_option($task, 'email')) {
// Email report for fsck
$fsck_report_mail = get_fsck_report();
$email_to = Config::get(CONFIG_EMAIL_TO);
Log::debug("Sending fsck report to $email_to");
mail($email_to, 'fsck of Greyhole shares on ' . exec('hostname'), $fsck_report_mail);
}
break;
case 'mkdir':
break;
case 'write':
gh_write($task->share, $task->full_path, $task->id);
break;
case 'rename':
$fix_symlinks_scanned_dirs = array();
gh_mv($task->share, $task->full_path, $task->additional_info, $task->id);
break;
case 'unlink':
gh_unlink($task->share, $task->full_path, $task->id);
break;
case 'rmdir':
gh_rmdir($task->share, $task->full_path);
break;
}
if ($task->action != 'write' && $task->action != 'rename') {
$sleep_before_task = array();
}
archive_task($task->id);
}
function archive_task($task_id) {
$query = "INSERT INTO tasks_completed SELECT * FROM tasks WHERE id = :task_id";
$worked = DB::insert($query, array('task_id' => $task_id));
if (!$worked) {
// Let's try a second time... This is kinda important!
DB::connect();
DB::insert($query, array('task_id' => $task_id));
}
$query = "DELETE FROM tasks WHERE id = :task_id";
DB::execute($query, array('task_id' => $task_id));
}
function gh_rmdir($share, $full_path) {
$landing_zone = get_share_landing_zone($share);
if (!$landing_zone) {
return;
}
Log::info("Directory deleted: $landing_zone/$full_path");
if (array_contains(ConfigHelper::$trash_share_names, $share)) {
// Remove that directory from all trashes
foreach (Config::storagePoolDrives() as $sp_drive) {
if (@rmdir("$sp_drive/.gh_trash/$full_path")) {
Log::debug(" Removed copy from trash at $sp_drive/.gh_trash/$full_path");
}
}
return;
}
foreach (Config::storagePoolDrives() as $sp_drive) {
if (@rmdir("$sp_drive/$share/$full_path/")) {
Log::debug(" Removed copy at $sp_drive/$share/$full_path");
}
$metastore = "$sp_drive/.gh_metastore";
if (@rmdir("$metastore/$share/$full_path/")) {
Log::debug(" Removed metadata files directory $metastore/$share/$full_path");
}
}
}
function gh_unlink($share, $full_path, $task_id) {
$landing_zone = get_share_landing_zone($share);
if (!$landing_zone) {
return;
}
if (should_ignore_file($share, $full_path)) {
return;
}
Log::info("File deleted: $landing_zone/$full_path");
if (array_contains(ConfigHelper::$trash_share_names, $share)) {
// Will delete the file in the trash which has no corresponding symlink in the Greyhole Trash share.
// That symlink is what was deleted from that share to create the task we're currently working on.
$full_path = preg_replace('/ copy [0-9]+$/', '', $full_path);
Log::debug(" Looking for corresponding file in trash to delete...");
foreach (Config::storagePoolDrives() as $sp_drive) {
if (file_exists("$sp_drive/.gh_trash/$full_path")) {
$delete = TRUE;
$trash_share = SharesConfig::getConfigForShare(CONFIG_TRASH_SHARE);
if ($trash_share) {
list($path, $filename) = explode_full_path("{$trash_share[CONFIG_LANDING_ZONE]}/$full_path");
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== FALSE) {
if ($file == '.' || $file == '..') { continue; }
if (is_link("$path/$file") && readlink("$path/$file") == "$sp_drive/.gh_trash/$full_path") {
$delete = FALSE;
continue;
}
}
}
}
if ($delete) {
Log::debug(" Deleting corresponding copy $sp_drive/.gh_trash/$full_path");
unlink("$sp_drive/.gh_trash/$full_path");
break;
}
}
}
return;
}
if (gh_file_exists("$landing_zone/$full_path") && !is_dir("$landing_zone/$full_path")) {
Log::debug(" File still exists in landing zone; a new file replaced the one deleted here. Skipping.");
return;
}
list($path, $filename) = explode_full_path($full_path);
foreach (get_metafiles($share, $path, $filename, TRUE) as $existing_metafiles) {
foreach ($existing_metafiles as $metafile) {
gh_recycle($metafile->path);
}
}
remove_metafiles($share, $path, $filename);
}
function is_a_metastore_dir($share, $full_path) {
foreach (get_metastores() as $metastore) {
if (is_dir("$metastore/$share/$full_path")) {
return TRUE;
}
}
return FALSE;
}
function gh_mv($share, $full_path, $target_full_path, $task_id) {
global $sleep_before_task;
$landing_zone = get_share_landing_zone($share);
if (!$landing_zone) {
return;
}
if (should_ignore_file($share, $target_full_path)) {
return;
}
if (is_dir("$landing_zone/$target_full_path") || is_a_metastore_dir($share, $full_path)) {
Log::info("Directory renamed: $landing_zone/$full_path -> $landing_zone/$target_full_path");
foreach (Config::storagePoolDrives() as $sp_drive) {
if (!is_greyhole_owned_drive($sp_drive)) {
continue;
}
list($original_path, $dirname) = explode_full_path(get_share_landing_zone($share) . "/$target_full_path");
if (is_dir("$sp_drive/$share/$full_path")) {
# Make sure the parent directory of target_full_path exists, before we try moving something there...
list($path, $dirname) = explode_full_path("$sp_drive/$share/$target_full_path");
gh_mkdir($path, $original_path);
gh_rename("$sp_drive/$share/$full_path", "$sp_drive/$share/$target_full_path");
Log::debug(" Directory moved: $sp_drive/$share/$full_path -> $sp_drive/$share/$target_full_path");
}
list($path, $dirname) = explode_full_path("$sp_drive/.gh_metastore/$share/$target_full_path");
gh_mkdir($path, $original_path);
$result = @gh_rename("$sp_drive/.gh_metastore/$share/$full_path", "$sp_drive/.gh_metastore/$share/$target_full_path");
if ($result) {
Log::debug(" Metadata Store directory moved: $sp_drive/.gh_metastore/$share/$full_path -> $sp_drive/.gh_metastore/$share/$target_full_path");
}
$result = @gh_rename("$sp_drive/.gh_metastore_backup/$share/$full_path", "$sp_drive/.gh_metastore_backup/$share/$target_full_path");
if ($result) {
Log::debug(" Backup Metadata Store directory moved: $sp_drive/.gh_metastore_backup/$share/$full_path -> $sp_drive/.gh_metastore_backup/$share/$target_full_path");
}
}
// Let look in the LZ too, for files we didn't process yet (maybe the folder was ignored before it was renamed)
exec('find ' . escapeshellarg("$landing_zone/$target_full_path") . ' -type f', $files_in_lz);
foreach ($files_in_lz as $file_in_lz) {
list($file_path, $filename) = explode_full_path($file_in_lz);
gh_fsck_file($file_path, $filename, 'file', 'landing_zone', $share);
}
foreach (get_metafiles($share, $target_full_path, null, FALSE, FALSE, FALSE) as $existing_metafiles) {
Log::debug("Existing metadata files: " . count($existing_metafiles));
foreach ($existing_metafiles as $file_path => $file_metafiles) {
Log::debug(" File metafiles: " . count($file_metafiles));
$new_file_metafiles = array();
$symlinked = FALSE;
foreach ($file_metafiles as $key => $metafile) {
$old_path = $metafile->path;
$metafile->path = str_replace("/$share/$full_path/$file_path", "/$share/$target_full_path/$file_path", $metafile->path);
Log::debug(" Changing metadata file: $old_path -> $metafile->path");
$new_file_metafiles[$metafile->path] = $metafile;
// is_linked = is the target of the existing symlink
if ($metafile->is_linked) {
$symlinked = TRUE;
$symlink_target = $metafile->path;
}
}
if (!$symlinked && count($file_metafiles) > 0) {
// None of the metafiles were is_linked; use the last one for the symlink.
$metafile->is_linked = TRUE;
$file_metafiles[$key] = $metafile;
$symlink_target = $metafile->path;
}
if (is_link("$landing_zone/$target_full_path/$file_path") && !empty($symlink_target) && readlink("$landing_zone/$target_full_path/$file_path") != $symlink_target) {
Log::debug(" Updating symlink at $landing_zone/$target_full_path/$file_path to point to $symlink_target");
unlink("$landing_zone/$target_full_path/$file_path");
symlink($symlink_target, "$landing_zone/$target_full_path/$file_path");
} else if (is_link("$landing_zone/$full_path/$file_path") && !empty($symlink_target) && !file_exists(readlink("$landing_zone/$full_path/$file_path"))) {
Log::debug(" Updating symlink at $landing_zone/$full_path/$file_path to point to $symlink_target");
unlink("$landing_zone/$full_path/$file_path");
symlink($symlink_target, "$landing_zone/$full_path/$file_path");
} else {
fix_symlinks($landing_zone, $share, "$full_path/$file_path", "$target_full_path/$file_path");
}
list($path, $filename) = explode_full_path("$target_full_path/$file_path");
save_metafiles($share, $path, $filename, $new_file_metafiles);
}
}
} else {
Log::info("File renamed: $landing_zone/$full_path -> $landing_zone/$target_full_path");
// Check if another process locked this file before we work on it.
global $locked_files;
if (isset($locked_files[clean_dir("$share/$target_full_path")]) || file_is_locked($share, $target_full_path) !== FALSE) {
Log::debug(" File $landing_zone/$target_full_path is locked by another process. Will wait until it's unlocked to work on it.");
postpone_task($task_id);
$locked_files[clean_dir("$share/$target_full_path")] = TRUE;
return;
}
list($path, $filename) = explode_full_path($full_path);
list($target_path, $target_filename) = explode_full_path($target_full_path);
foreach (get_metafiles($share, $path, $filename, FALSE, FALSE, FALSE) as $existing_metafiles) {
// There might be old metafiles... for example, when a delete task was skipped.
// Let's remove the file copies if there are any leftovers; correct copies will be re-created below.
if (file_exists("$landing_zone/$target_full_path") && (count($existing_metafiles) > 0 || !is_link("$landing_zone/$target_full_path"))) {
foreach (get_metafiles($share, $target_path, $target_filename, TRUE, FALSE, FALSE) as $existing_target_metafiles) {
if (count($existing_target_metafiles) > 0) {
foreach ($existing_target_metafiles as $metafile) {
gh_recycle($metafile->path);
}
remove_metafiles($share, $target_path, $target_filename);
}
}
}
if (count($existing_metafiles) == 0) {
// Any NOK metafiles that need to be removed?
foreach (get_metafiles($share, $path, $filename, TRUE, FALSE, FALSE) as $all_existing_metafiles) {
if (count($all_existing_metafiles) > 0) {
remove_metafiles($share, $path, $filename);
}
}
// New file
gh_write($share, $target_full_path, $task_id);
} else {
$symlinked = FALSE;
foreach ($existing_metafiles as $key => $metafile) {
$old_path = $metafile->path;
$metafile->path = str_replace("/$share/$full_path", "/$share/$target_full_path", $old_path);
Log::debug(" Renaming copy at $old_path to $metafile->path");
// Make sure the target directory exists
list($metafile_dir_path, $metafile_filename) = explode_full_path($metafile->path);
list($original_path, $dirname) = explode_full_path(get_share_landing_zone($share) . "/$target_full_path");
gh_mkdir($metafile_dir_path, $original_path);
$it_worked = gh_rename($old_path, $metafile->path);
if ($it_worked) {
// is_linked = is the target of the existing symlink
if ($metafile->is_linked) {
$symlinked = TRUE;
$symlink_target = $metafile->path;
}
} else {
Log::warn(" Warning! An error occured while renaming file copy $old_path to $metafile->path.");
}
$existing_metafiles[$key] = $metafile;
}
if (!$symlinked && count($existing_metafiles) > 0) {
// None of the metafiles were is_linked; use the last one for the symlink.
$metafile->is_linked = TRUE;
$existing_metafiles[$key] = $metafile;
$symlink_target = $metafile->path;
}
remove_metafiles($share, $path, $filename);
save_metafiles($share, $target_path, $target_filename, $existing_metafiles);
if (is_link("$landing_zone/$target_full_path")) {
// New link exists...
if (readlink("$landing_zone/$target_full_path") != $symlink_target) {
// ...and needs to be updated.
Log::debug(" Updating symlink at $landing_zone/$target_full_path to point to $symlink_target");
unlink("$landing_zone/$target_full_path");
symlink($symlink_target, "$landing_zone/$target_full_path");
}
} else if (is_link("$landing_zone/$full_path") && !file_exists(readlink("$landing_zone/$full_path"))) {
Log::debug(" Updating symlink at $landing_zone/$full_path to point to $symlink_target");
unlink("$landing_zone/$full_path");
symlink($symlink_target, "$landing_zone/$full_path");
} else {
fix_symlinks($landing_zone, $share, $full_path, $target_full_path);
}
}
}
}
$sleep_before_task = array();
}
function fix_symlinks($landing_zone, $share, $full_path, $target_full_path) {
global $fix_symlinks_scanned_dirs;
if (isset($fix_symlinks_scanned_dirs[$landing_zone])) {
return;
}
Log::info(" Scanning $landing_zone for broken links... This can take a while!");
exec("find -L " . escapeshellarg($landing_zone) . " -type l", $broken_links);
Log::debug(" Found " . count($broken_links) . " broken links.");
foreach ($broken_links as $broken_link) {
$fixed_link_target = readlink($broken_link);
foreach (Config::storagePoolDrives() as $sp_drive) {
$fixed_link_target = str_replace(clean_dir("$sp_drive/$share/$full_path/"), clean_dir("$sp_drive/$share/$target_full_path/"), $fixed_link_target);
if ($fixed_link_target == "$sp_drive/$share/$full_path") {
$fixed_link_target = "$sp_drive/$share/$target_full_path";
break;
}
}
if (gh_is_file($fixed_link_target)) {
Log::debug(" Found a broken symlink to update: $broken_link. Old (broken) target: " . readlink($broken_link) . "; new (fixed) target: $fixed_link_target");
unlink($broken_link);
symlink($fixed_link_target, $broken_link);
}
}
$fix_symlinks_scanned_dirs[$landing_zone] = TRUE;
}
function gh_file_exists($real_path, $log_message=null) {
clearstatcache();
if (!file_exists($real_path)) {
if ($log_message != null) {
eval('$log_message = "' . str_replace('"', '\"', $log_message) . '";');
Log::info($log_message);
}
return FALSE;
}
return TRUE;
}
function get_num_copies($share) {
$num_copies = SharesConfig::get($share, CONFIG_NUM_COPIES);
if (!$num_copies) {
Log::warn("Found a task on a share ($share) that disappeared from " . ConfigHelper::$config_file . ". Skipping.");
return -1;
}
if ($num_copies < 1) {
$num_copies = 1;
}
$max_copies = 0;
foreach (Config::storagePoolDrives() as $sp_drive) {
if (is_greyhole_owned_drive($sp_drive)) {
$max_copies++;
}
}
if ($num_copies > $max_copies) {
$num_copies = $max_copies;
}
return $num_copies;
}
function file_is_locked($share, $full_path) {
if (Config::get(CONFIG_CHECK_FOR_OPEN_FILES) === FALSE) {
Log::debug(" Skipping open file (lock) check.");
return FALSE;
}
$landing_zone = get_share_landing_zone($share);
if (!$landing_zone) {
return FALSE;
}
$real_fullpath = "$landing_zone/$full_path";
if (is_link($real_fullpath)) {
$real_fullpath = readlink($real_fullpath);
}
$result = exec("lsof -M -n -P -l " . escapeshellarg($real_fullpath) . " 2> /dev/null");
if (string_contains($result, $real_fullpath)) {
return $result;
}
$query = "SELECT * FROM tasks WHERE complete = 'no' AND action = 'write' AND share = :share AND full_path = :full_path LIMIT 1";
$params = array('share' => $share, 'full_path' => $full_path);
$row = DB::getFirst($query, $params);
if ($row === FALSE) {
return FALSE;
}
// Locked, according to DB... But maybe it's not really locked?
if (!gh_file_exists($real_fullpath)) {
// File doesn't exists anymore... It can't be really locked... Let's assume this is just Samba that 'forgot' to close the file handle.
$query = "UPDATE tasks SET complete = 'yes' WHERE complete = 'no' AND action = 'write' AND share = :share AND full_path = :full_path";
DB::execute($query, $params);
return FALSE;
}
return TRUE;
}
function real_file_is_locked($real_fullpath) {
if (is_link($real_fullpath)) {
$real_fullpath = readlink($real_fullpath);
}
$result = exec("lsof -M -n -P -l " . escapeshellarg($real_fullpath) . " 2> /dev/null");
if (string_contains($result, $real_fullpath)) {
return $result;
}
return FALSE;
}
function find_future_full_path($share, $full_path, $task_id) {
$new_full_path = $full_path;
while ($next_task = find_next_rename_task($share, $new_full_path, $task_id)) {
if ($next_task->full_path == $full_path) {
// File was renamed
$new_full_path = $next_task->additional_info;
} else {
// A parent directory was renamed
$new_full_path = preg_replace("@^$next_task->full_path@", $next_task->additional_info, $new_full_path);
}
$task_id = $next_task->id;
}
return $new_full_path;
}
function find_next_rename_task($share, $full_path, $task_id) {
$full_paths = array();
$full_paths[] = $full_path;
$parent_full_path = $full_path;
list($parent_full_path, $basename) = explode_full_path($parent_full_path);
while (strlen($parent_full_path) > 1) {
$full_paths[] = $parent_full_path;
list($parent_full_path, $basename) = explode_full_path($parent_full_path);
}
$query = "SELECT * FROM tasks WHERE complete = 'yes' AND share = :share AND action = 'rename' AND full_path IN ('" . implode("','", array_map("DB::quote", $full_paths)) . "') AND id > :task_id ORDER BY id LIMIT 1";
return DB::getFirst($query, array('share' => $share, 'task_id' => $task_id));
}
function should_ignore_file($share, $full_path) {
list($path, $filename) = explode_full_path($full_path);
foreach (Config::get(CONFIG_IGNORED_FILES) as $ignored_file_re) {
if (preg_match(';^' . $ignored_file_re . '$;', $filename)) {
Log::info("Ignoring task because it matches the following '" . CONFIG_IGNORED_FILES . "' pattern: $ignored_file_re");
return TRUE;
}
}
foreach (Config::get(CONFIG_IGNORED_FOLDERS) as $ignored_folder_re) {
$p = clean_dir("$share/$path");
if (preg_match(';^' . $ignored_folder_re . '$;', $p)) {
Log::info("Ignoring task because it matches the following '" . CONFIG_IGNORED_FOLDERS . "' pattern: $ignored_folder_re");
return TRUE;
}
}
return FALSE;
}
function gh_write($share, $full_path, $task_id) {
global $sleep_before_task;
$landing_zone = get_share_landing_zone($share);
if (!$landing_zone) {
return;
}
if (should_ignore_file($share, $full_path)) {
return;
}
if (!gh_file_exists("$landing_zone/$full_path", '$real_path doesn\'t exist anymore.')) {
$new_full_path = find_future_full_path($share, $full_path, $task_id);
if ($new_full_path != $full_path && gh_is_file("$landing_zone/$new_full_path")) {
Log::debug(" Found that $full_path has been renamed to $new_full_path. Will work using that instead.");
if (is_link("$landing_zone/$new_full_path")) {
$source_file = clean_dir(readlink("$landing_zone/$new_full_path"));
} else {
$source_file = clean_dir("$landing_zone/$new_full_path");
}
} else {
Log::info(" Skipping.");
if (!gh_file_exists($landing_zone, ' Share "' . $share . '" landing zone "$real_path" doesn\'t exist anymore. Will not process this task until it re-appears...')) {
postpone_task($task_id);
}
return;
}
}
$num_copies_required = get_num_copies($share);
if ($num_copies_required === -1) {
return;
}
list($path, $filename) = explode_full_path($full_path);
if ((isset($new_full_path) && is_link("$landing_zone/$new_full_path")) || is_link("$landing_zone/$full_path")) {
if (!isset($source_file)) {
$source_file = clean_dir(readlink("$landing_zone/$full_path"));
}
clearstatcache();
$filesize = gh_filesize($source_file);
if (Log::getLevel() >= Log::DEBUG) {
Log::info("File changed: $share/$full_path - " . bytes_to_human($filesize, FALSE));
} else {
Log::info("File changed: $share/$full_path");
}
Log::debug(" Will use source file: $source_file");
foreach (get_metafiles($share, $path, $filename, TRUE) as $existing_metafiles) {
// Remove old copies (but not the one that was updated!)
$keys_to_remove = array();
$found_source_file = FALSE;
foreach ($existing_metafiles as $key => $metafile) {
$metafile->path = clean_dir($metafile->path);
if ($metafile->path == $source_file) {
$metafile->is_linked = TRUE;
$metafile->state = 'OK';
$found_source_file = TRUE;
} else {
Log::debug(" Will remove copy at $metafile->path");
$keys_to_remove[] = $metafile->path;
}
}
if (!$found_source_file && count($keys_to_remove) > 0) {
// This shouldn't happen, but if we're about to remove all copies, let's make sure we keep at least one.
$key = array_shift($keys_to_remove);
$source_file = $existing_metafiles[$key]->path;
Log::debug(" Change of mind... Will use source file: $source_file");
}
$new_metafiles = gh_write_process_metafiles($num_copies_required, $existing_metafiles, $share, $full_path, $source_file, $filesize, $task_id, $keys_to_remove);
if (!empty($new_metafiles) && !isset($new_metafiles[$source_file])) {
// Delete source file; we copied it somewhere else
// Let's just make sure we have at least one OK file before we delete it!
Log::debug(" Source file is not needed anymore. Deleting...");
$is_ok = FALSE;
foreach ($new_metafiles as $metafile) {
if ($metafile->state == 'OK') {
$is_ok = TRUE;
break;
}
}
if ($is_ok) {
// check if setting is enabled
if (SharesConfig::get($share, CONFIG_MODIFIED_MOVES_TO_TRASH)) {
// Ok, now we're sure.
gh_recycle($source_file);
}
} else {
Log::debug(" Change of mind... Couldn't find any OK metadata file... Will keep the source!");
}
}
}
} else {
if (!isset($source_file)) {
$source_file = clean_dir("$landing_zone/$full_path");
}
clearstatcache();
$filesize = gh_filesize($source_file);
if (Log::getLevel() >= Log::DEBUG) {
Log::info("File created: $share/$full_path - " . bytes_to_human($filesize, FALSE));
} else {
Log::info("File created: $share/$full_path");
}
if (is_dir($source_file)) {
Log::info("$share/$full_path is now a directory! Aborting.");
return;
}
// There might be old metafiles... for example, when a delete task was skipped.
// Let's remove the file copies if there are any leftovers; correct copies will be re-created in create_copies_from_metafiles()
foreach (get_metafiles($share, $path, $filename) as $existing_metafiles) {
Log::debug(count($existing_metafiles) . " metafiles loaded.");
if (count($existing_metafiles) > 0) {
foreach ($existing_metafiles as $metafile) {
gh_recycle($metafile->path);
}
remove_metafiles($share, $path, $filename);
$existing_metafiles = array();
// Maybe there's other file copies, that weren't metafiles, or were NOK metafiles!
foreach (Config::storagePoolDrives() as $sp_drive) {
if (file_exists("$sp_drive/$share/$path/$filename")) {
gh_recycle("$sp_drive/$share/$path/$filename");
}
}
}
gh_write_process_metafiles($num_copies_required, $existing_metafiles, $share, $full_path, $source_file, $filesize, $task_id);
}
}
}
function gh_write_process_metafiles($num_copies_required, $existing_metafiles, $share, $full_path, $source_file, $filesize, $task_id, $keys_to_remove=NULL) {
$landing_zone = get_share_landing_zone($share);
list($path, $filename) = explode_full_path($full_path);
// Only need to check for locking if we have something to do!
if ($num_copies_required > 1 || count($existing_metafiles) == 0) {
// Check if another process locked this file before we work on it.
global $locked_files;
if (isset($locked_files[clean_dir("$share/$full_path")]) || ($locked_by = file_is_locked($share, $full_path)) !== FALSE) {
Log::debug(" File $landing_zone/$full_path is locked by another process. Will wait until it's unlocked to work on it.");
postpone_task($task_id);
$locked_files[clean_dir("$share/$full_path")] = TRUE;
return array();
}
$sleep_before_task = array();
}
if ($keys_to_remove !== NULL) {
foreach ($keys_to_remove as $key) {
if ($existing_metafiles[$key]->path != $source_file) {
// check if setting is enabled
if (SharesConfig::get($share, CONFIG_MODIFIED_MOVES_TO_TRASH)) {
// Ok, now we're sure.
gh_recycle($existing_metafiles[$key]->path);
}
}
}
// Empty the existing metafiles array, to be able to recreate all new copies on the correct drives, per the dir_selection_algorithm
$existing_metafiles = array();
}
$metafiles = create_metafiles($share, $full_path, $num_copies_required, $filesize, $existing_metafiles);
if (count($metafiles) == 0) {
Log::warn(" No metadata files could be created. Will wait until metadata files can be created to work on this file.");
postpone_task($task_id);
return array();
}
if (!is_link("$landing_zone/$full_path")) {
// Use the 1st metafile for the symlink; it might be on a sticky drive.
$i = 0;
foreach ($metafiles as $metafile) {
$metafile->is_linked = ($i++ == 0);
}
}
save_metafiles($share, $path, $filename, $metafiles);
create_copies_from_metafiles($metafiles, $share, $full_path, $source_file);
return $metafiles;
}
function create_copies_from_metafiles($metafiles, $share, $full_path, $source_file, $missing_only=FALSE) {
$landing_zone = get_share_landing_zone($share);
list($path, $filename) = explode_full_path($full_path);
$source_file = clean_dir($source_file);
$link_next = FALSE;
$file_infos = gh_get_file_infos("$landing_zone/$full_path");
foreach ($metafiles as $key => $metafile) {
if (!gh_file_exists("$landing_zone/$full_path", ' $real_path doesn\'t exist anymore. Aborting.')) { return; }
if ($metafile->path == $source_file && $metafile->state == 'OK' && gh_filesize($metafile->path) == gh_filesize($source_file)) {
Log::debug(" File copy at $metafile->path is already up to date.");
continue;
}
if ($missing_only && gh_file_exists($metafile->path) && $metafile->state == 'OK' && gh_filesize($metafile->path) == gh_filesize($source_file)) {
Log::debug(" File copy at $metafile->path is already up to date.");
continue;
}
$root_path = str_replace(clean_dir("/$share/$full_path"), '', $metafile->path);
if (!is_greyhole_owned_drive($root_path)) {
Log::warn(" Warning! It seems the partition UUID of $root_path changed. This probably means this mount is currently unmounted, or that you replaced this drive and didn't use 'greyhole --replace'. Because of that, Greyhole will NOT use this drive at this time.");
$metafile->state = 'Gone';
$metafiles[$key] = $metafile;
continue;
}
list($metafile_dir_path, $metafile_filename) = explode_full_path($metafile->path);
list($original_path, $metafile_filename) = explode_full_path(get_share_landing_zone($share) . "/$full_path");
if (!gh_mkdir($metafile_dir_path, $original_path)) {
$metafile->state = 'Gone';
$metafiles[$key] = $metafile;
continue;
}
if (!gh_copy_file($source_file, $metafile->path)) {
if ($metafile->is_linked) {
$metafile->is_linked = FALSE;
$link_next = TRUE;
}
$metafile->state = 'Gone';
gh_recycle($metafile->path);
$metafiles[$key] = $metafile;
save_metafiles($share, $path, $filename, $metafiles);