forked from gboudreau/Greyhole
-
Notifications
You must be signed in to change notification settings - Fork 0
/
greyhole
executable file
·4987 lines (4479 loc) · 222 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-2012 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/>.
*/
include('includes/common.php');
list($action, $options) = process_command_line();
if ($action == 'unknown') {
print_usage();
}
// Any forking needs to happen before db_connect, or the parent exiting will close the child's DB connection!
if ($action == 'md5-worker') {
$pid = pcntl_fork();
if ($pid == -1) {
die("Error spawning child md5-worker!");
}
if ($pid == 0) {
// Child
} else {
// Parent
echo $pid;
exit(0);
}
}
process_config();
db_connect() or gh_log(CRITICAL, "Can't connect to $db_options->engine database: " . db_error());
db_migrate();
if ($action != 'stats' && $action != 'view-queue' && $action != 'debug' && $action != 'iostat' && $action != 'status' && $action != 'getuid' && $action != 'logs') {
if (exec("whoami") != 'root') {
echo "You need to execute this as root.\n";
exit(1);
}
}
if ($action == 'pause') {
$pid = (int) exec('ps ax | grep "greyhole --daemon\|greyhole -D" | grep -v grep | awk \'{print $1}\'');
if ($pid) {
exec('kill -STOP ' . $pid);
echo "The Greyhole deamon has been paused. Use 'greyhole --resume' to restart it.\n";
exit(0);
} else {
echo "Couldn't find a Greyhole daemon running.\n";
exit(1);
}
}
if ($action == 'resume') {
$pid = (int) exec('ps ax | grep "greyhole --daemon\|greyhole -D" | grep -v grep | awk \'{print $1}\'');
if ($pid) {
exec('kill -CONT ' . $pid);
echo "The Greyhole deamon has resumed.\n";
exit(0);
} else {
echo "Couldn't find a Greyhole daemon running.\n";
exit(1);
}
}
if ($action == 'getuid') {
$uniq_id = set_uniq_id();
echo $uniq_id;
exit(0);
}
if ($action == 'logs') {
if (strtolower($greyhole_log_file) == 'syslog') {
if (gh_is_file('/var/log/syslog')) {
passthru("tail -F -n 1 /var/log/syslog | grep --line-buffered Greyhole");
} else {
passthru("tail -F -n 1 /var/log/messages | grep --line-buffered Greyhole");
}
} else {
$files = escapeshellarg($greyhole_log_file);
passthru("tail -n 1 $files");
if (!empty($greyhole_error_log_file)) {
$files = escapeshellarg($greyhole_error_log_file) . " " . $files;
}
passthru("tail -qF -n 0 $files");
}
exit(0);
}
if ($action == 'iostat') {
$devices_drives = array();
foreach ($storage_pool_drives as $sp_drive) {
$device = exec("df " . escapeshellarg($sp_drive) . " 2>/dev/null | awk '{print \$1}'");
$device = preg_replace('@/dev/(sd[a-z])[0-9]+@', '\1', $device);
$devices_drives[$device] = $sp_drive;
}
while (TRUE) {
unset($result);
exec("iostat -p ALL -k 10 2 | grep '^sd[a-z] ' | awk '{print \$1,\$3,\$4}'", $result);
$iostat = array();
foreach ($result as $line) {
$info = explode(' ', $line);
$device = $info[0];
$read_kBps = $info[1];
$write_kBps = $info[2];
if (!isset($devices_drives[$device])) {
# That device isn't in the storage pool.
continue;
}
$drive = $devices_drives[$device];
$iostat[$drive] = (int) round($read_kBps + $write_kBps);
}
#ksort($iostat); // Let keep the order in which the drives were mounted
foreach ($iostat as $drive => $io_kBps) {
printf("$drive: %7s kBps\n", $io_kBps);
}
echo "---\n";
}
exit(0);
}
if ($action == 'thaw') {
if (isset($options['dir']) && array_search($options['dir'], $frozen_directories) === FALSE) {
$options['dir'] = '/' . trim($options['dir'], '/');
}
if (!isset($options['dir']) || array_search($options['dir'], $frozen_directories) === FALSE) {
echo "Frozen directories:\n";
foreach ($frozen_directories as $frozen_directory) {
echo " $frozen_directory\n";
}
echo "To thaw any of the above directories, use the following command:\n";
echo "greyhole --thaw=directory\n";
exit(0);
}
$path = explode('/', $options['dir']);
$share = array_shift($path);
$query = sprintf("UPDATE tasks SET complete = 'thawed' WHERE complete = 'frozen' AND share = '%s' AND full_path LIKE '%s%%'",
db_escape_string($share),
db_escape_string(implode('/', $path))
);
db_query($query) or die("Can't thaw tasks with query: $query - Error: " . db_error());
echo $options['dir'] . " directory has been thawed.\n";
echo "All pasts file operations that occured in this directory will now be processed by Greyhole.\n";
exit(0);
}
if ($action == 'fix-symlinks') {
fix_all_symlinks();
exit(0);
}
if ($action == 'delete-metadata') {
$share = trim(mb_substr($options['dir'], 0, mb_strpos($options['dir'], '/')+1), '/');
$full_path = trim(mb_substr($options['dir'], mb_strpos($options['dir'], '/')+1), '/');
list($path, $filename) = explode_full_path($full_path);
set_metastore_backup();
foreach (get_metafile_data_filenames($share, $path, $filename) as $file) {
if (file_exists($file)) {
echo "Deleting $file\n";
unlink($file);
}
}
echo "Done.\n";
exit(0);
}
if ($action == 'remove-share') {
$share = $options['dir'];
if (!isset($shares_options[$share])) {
echo "'$share' is not a known share.\n";
echo "If you removed it already from your Greyhole configuration, please re-add it, and retry.\n";
echo "Otherwise, please use one of the following share name:\n";
echo " " . implode("\n ", array_keys($shares_options)) . "\n";
exit(1);
}
$landing_zone = get_share_landing_zone($share);
echo "Will remove '$share' share from the Greyhole storage pool, by moving all the data files inside this share to it's landing zone: $landing_zone\n";
// df the landing zone, to see how much free space it has
$free_space = 1024 * exec("df -k --total " . escapeshellarg($landing_zone) . " | awk '/^total/{print $4}'");
// du the files to see if there's room in the landing zone
echo " Finding how much space is needed, and if you have enough... Please wait...\n";
$space_needed = 1024 * exec("du -skL " . escapeshellarg($landing_zone) . " | awk '{print $1}'");
echo " Space needed: " . bytes_to_human($space_needed, FALSE) . "\n";
echo " Free space: " . bytes_to_human($free_space, FALSE) . "\n";
// Adjust the landing zone free space, if some file copies are already on that drive
$storage_pool_drives_to_unwind = array();
foreach ($storage_pool_drives as $sp_drive) {
if (!file_exists("$sp_drive/$share")) {
#echo " Folder does not exist: $sp_drive/$share. Skipping.\n";
continue;
}
if (gh_dir_uuid("$sp_drive/$share") === gh_dir_uuid("$landing_zone")) {
$more_free_space = 1024 * exec("du -sk " . escapeshellarg("$sp_drive/$share") . " | awk '{print $1}'");
$free_space += $more_free_space;
echo " + " . bytes_to_human($more_free_space, FALSE) . " (file copies already on $sp_drive) = " . bytes_to_human($free_space, FALSE) . " (Total available space)\n";
// We also need to make sure this drive is 'unwind' first, to make sure it will have enough free space to receive all the file copies.
array_unshift($storage_pool_drives_to_unwind, $sp_drive);
} else {
array_push($storage_pool_drives_to_unwind, $sp_drive);
}
}
if ($space_needed > $free_space) {
echo "Not enough free space available in $landing_zone. Aborting.\n";
exit(1);
}
echo " OK! Let's do this.\n";
// Remove the symlinks from the landing zone
echo " Deleting symlinks from landing zone... Please wait...\n";
exec("find " . escapeshellarg($landing_zone) . " -type l -delete");
echo " Done.\n";
// Copy the data files from the storage pool into the landing zone
$num_files_total = 0;
foreach ($storage_pool_drives_to_unwind as $sp_drive) {
unset($result);
echo " Moving files from $sp_drive/$share into $landing_zone... Please wait...\n";
exec("rsync -rlptgoDuvW --remove-source-files " . escapeshellarg("$sp_drive/$share/") . " " . escapeshellarg('/' . trim($landing_zone, '/')), $result);
$num_files = count($result)-5;
if ($num_files < 0) {
$num_files = 0;
}
$num_files_total += $num_files;
exec("find " . escapeshellarg("$sp_drive/$share/") . " -type d -delete");
echo " Done. Copied $num_files files.\n";
}
echo "All done. Copied $num_files_total files.\nYou should now remove the Greyhole options from the [$share] share in your smb.conf.\n";
exec("/bin/sed -i 's/^.*num_copies\[".$share."\].*$//' " . escapeshellarg($config_file));
restart_service();
exit(0);
}
if ($action == 'gone' || $action == 'going') {
if (array_search(@$options['drive'], $storage_pool_drives) === FALSE) {
$options['drive'] = '/' . trim(@$options['drive'], '/');
}
if (array_search($options['drive'], $storage_pool_drives) === FALSE) {
if (!empty($options['drive'])) {
echo "Directory " . $options['drive'] . " is not one of your defined storage pool drives.\n";
}
echo "Please use one of the following with the --$action option:\n ";
echo implode("\n ", $storage_pool_drives) . "\n";
echo "Note that the correct syntax for this command is:\n";
echo " greyhole --$action=<drive>\n";
echo "The '=' character is mandatory.\n";
exit(1);
}
if ($action == 'going') {
// Check that all scheduled fsck have completed; an incomplete fsck means some file copies might be missing!
$result = db_query("SELECT COUNT(*) AS total FROM tasks WHERE action = 'fsck'") or die("Can't query tasks for pending fsck operations. Error: " . db_error());
$row = db_fetch_object($result);
if ($row->total > 0) {
echo "There are pending fsck operations. This could mean some file copies are missing, which would make it dangerous to remove a drive at this time.\n";
echo "Please wait until all fsck operation are complete, and then retry.\n";
exit(2);
}
}
// Removing this drive here will insure it won't be used for new files while we're moving files away, and that it can later be replaced.
remove_drive_definition($options['drive']);
if ($action == 'going') {
file_put_contents($options['drive'] . "/.greyhole_used_this", "Flag to prevent Greyhole from thinking this drive disappeared for no reason...");
set_metastore_backup();
gh_log(INFO, "Storage pool drive " . $options['drive'] . " will be removed from the storage pool.");
echo("\nStorage pool drive " . $options['drive'] . " will be removed from the storage pool. This can take a while, please be patient.\n");
// global $going_drive; // Used in function is_greyhole_owned_drive()
$going_drive = $options['drive'];
// For the fsck_file calls to be able to use the files on $going_drive if needed, to create extra copies.
global $options;
$options['find-orphans'] = TRUE;
// fsck shares with only 1 file copy to remove those from $going_drive
initialize_fsck_report('Shares with only 1 copy');
foreach ($shares_options as $share_name => $share_options) {
echo "\n";
if ($share_options['num_copies'] == 1) {
echo "Moving file copies for share '$share_name'... ";
if (is_dir("$going_drive/$share_name")) {
gh_fsck_reset_du($share_name);
gh_fsck($share_options['landing_zone'], $share_name);
}
echo "Done.\n";
} else {
// Temporarily rename $going_drive/$share_name for fix_symlinks_on_share to be able to find symlinks that will be broken once this drive is removed.
rename("$going_drive/$share_name", "$going_drive/$share_name".".tmp");
fix_symlinks_on_share($share_name);
rename("$going_drive/$share_name".".tmp", "$going_drive/$share_name");
// Also, just to be safe, make sure that all the files in $going_drive/$share_name are also somewhere else, as expected.
echo "Checking that all the files in the share '$share_name' also exist on another drive...";
check_going_dir("$going_drive/$share_name", $share_name, $going_drive);
echo " Done.\n";
}
}
}
// Remove $going_drive from config file and restart (if it was running)
$escaped_drive = str_replace('/', '\/', $options['drive']);
exec("/bin/sed -i 's/^.*storage_pool_directory.*$escaped_drive.*$//' " . escapeshellarg($config_file)); // Deprecated notation
exec("/bin/sed -i 's/^.*storage_pool_drive.*$escaped_drive.*$//' " . escapeshellarg($config_file));
restart_service();
// For Amahi users
if (file_exists('/usr/bin/hdactl')) {
echo "\nYou should de-select this partition in your Amahi dashboard (http://hda), in the Shares > Storage Pool page.\n";
}
mark_gone_ok($options['drive'], 'remove');
mark_gone_drive_fscked($options['drive'], 'remove');
gh_log(INFO, "Storage pool drive " . $options['drive'] . " has been removed.");
echo "\nStorage pool drive " . $options['drive'] . " has been removed from your pool, which means the missing file copies that are in this drive will be re-created during the next fsck.\n";
if ($action == 'going') {
// Schedule fsck for all shares to re-create missing copies on other shares
schedule_fsck_all_shares(array('email'));
echo "All the files that were only on $going_drive have been copied somewhere else.\n";
echo "A fsck of all shares has been scheduled, to recreate other file copies. It will start after all currently pending tasks have been completed, and you will receive email reports when it completes.\n";
unlink($options['drive'] . "/.greyhole_used_this");
} else { // $action == 'gone'
echo "Sadly, file copies that were only on this drive, if any, are now lost!\n";
}
echo "\n";
exit(0);
}
function check_going_dir($path, $share, $going_drive) {
$handle = @opendir($path);
if ($handle === FALSE) {
gh_log(ERROR, "Couldn't open $path to list content. Skipping...");
return;
}
gh_log(DEBUG, "Entering $path");
while (($filename = readdir($handle)) !== FALSE) {
if ($filename == '.' || $filename == '..') { continue; }
$full_path = "$path/$filename";
$file_type = @filetype($full_path);
if ($file_type === FALSE) {
// Try NFC form [http://en.wikipedia.org/wiki/Unicode_equivalence#Normalization]
$file_type = @filetype(normalize_utf8_characters($full_path));
if ($file_type !== FALSE) {
// Bingo!
$full_path = normalize_utf8_characters($full_path);
$path = normalize_utf8_characters($path);
}
}
if ($file_type == 'dir') {
check_going_dir($full_path, $share, $going_drive);
} else {
$file_path = trim(mb_substr($path, mb_strlen("$going_drive/$share")+1), '/');
$file_metafiles = array();
$file_copies_inodes = get_file_inodes($share, $file_path, $filename, $file_metafiles, TRUE);
if (count($file_copies_inodes) == 0) {
gh_log(WARN, "Found a file, $full_path, that has no other copies on other drives. Removing $going_drive would make that file disappear! Will create extra copies now.");
echo ".";
gh_fsck_file($path, $filename, $file_type, 'landing_zone', $share, $going_drive);
}
}
}
closedir($handle);
}
if ($action == 'debug') {
if (!isset($options['debug_filename'])) {
print_usage();
}
$filename = $options['debug_filename'];
if (mb_strpos($filename, '/') === FALSE) {
$filename = "/$filename";
}
echo "Debugging file operations for file named \"$filename\"\n";
echo "\nFrom DB\n=======\n";
$debug_tasks = array();
$query = sprintf("SELECT id, action, share, full_path, additional_info, event_date FROM tasks_completed WHERE full_path LIKE '%%%s%%' ORDER BY id ASC",
db_escape_string($filename)
);
$result = db_query($query) or die("Can't query tasks_completed with query: $query - Error: " . db_error());
while ($row = db_fetch_object($result)) {
$debug_tasks[$row->id] = $row;
}
// Renames
$query = sprintf("SELECT id, action, share, full_path, additional_info, event_date FROM tasks_completed WHERE additional_info LIKE '%%%s%%' ORDER BY id ASC",
db_escape_string($filename)
);
while (TRUE) {
$result = db_query($query) or die("Can't query tasks_completed for renames with query: $query - Error: " . db_error());
while ($row = db_fetch_object($result)) {
$debug_tasks[$row->id] = $row;
$query = sprintf("SELECT id, action, share, full_path, additional_info, event_date FROM tasks_completed WHERE additional_info = '%s' ORDER BY id ASC",
db_escape_string($row->full_path)
);
}
# Is there more?
$new_query = preg_replace('/SELECT .* FROM/i', 'SELECT COUNT(*) FROM', $query);
$result = db_query($new_query) or die("Can't query tasks_completed for COUNT of renames with query: $new_query - Error: " . db_error());
if (db_fetch_object($result) !== FALSE) {
break;
}
}
ksort($debug_tasks);
$to_grep = array();
foreach ($debug_tasks as $task) {
echo " [$task->event_date] Task ID $task->id: $task->action $task->share/$task->full_path" . ($task->action == 'rename' ? " -> $task->share/$task->additional_info" : '') . "\n";
$to_grep["$task->share/$task->full_path"] = 1;
if ($task->action == 'rename') {
$to_grep["$task->share/$task->additional_info"] = 1;
}
}
if (empty($to_grep)) {
$to_grep[$filename] = 1;
if (mb_strpos($filename, '/') !== FALSE) {
$share = trim(mb_substr($filename, 0, mb_strpos(mb_substr($filename, 1), '/')+1), '/');
$full_path = trim(mb_substr($filename, mb_strpos(mb_substr($filename, 1), '/')+1), '/');
$debug_tasks[] = (object) array('share' => $share, 'full_path' => $full_path);
}
}
echo "\nFrom logs\n=========\n";
$to_grep = array_keys($to_grep);
$to_grep = implode("|", $to_grep);
$commands = array();
$commands[] = "zgrep -h -E -B 1 -A 2 -h " . escapeshellarg($to_grep) . " $greyhole_log_file*.gz";
$commands[] = "grep -h -E -B 1 -A 2 -h " . escapeshellarg($to_grep) . " " . escapeshellarg($greyhole_log_file);
foreach ($commands as $command) {
exec($command, $result);
}
$result2 = array();
$i = 0;
foreach ($result as $rline) {
if ($rline == '--') { continue; }
$date_time = substr($rline, 0, 15);
$timestamp = strtotime($date_time);
$result2[$timestamp.sprintf("%04d", $i++)] = $rline;
}
ksort($result2);
echo implode("\n", $result2) . "\n";
echo "\nFrom filesystem\n===============\n";
$last_task = array_pop($debug_tasks);
$share = $last_task->share;
$full_path = $last_task->full_path;
list($path, $filename) = explode_full_path($full_path);
echo "Landing Zone:\n";
echo " "; passthru("ls -l " . escapeshellarg(get_share_landing_zone($share) . "/" . $full_path));
echo "\nMetadata Store:\n";
foreach ($storage_pool_drives as $sp_drive) {
$metastore = clean_dir("$sp_drive/.gh_metastore");
if (file_exists("$metastore/$share/$full_path")) {
echo " "; passthru("ls -l " . escapeshellarg("$metastore/$share/$full_path"));
$data = var_export(unserialize(file_get_contents("$metastore/$share/$full_path")), TRUE);
$data = str_replace("\n", "\n ", $data);
echo " $data\n";
}
}
echo "\nFile copies:\n";
foreach ($storage_pool_drives as $sp_drive) {
if (file_exists("$sp_drive/$share/$full_path")) {
echo " "; passthru("ls -l " . escapeshellarg("$sp_drive/$share/$full_path"));
}
}
exit(0);
}
if ($action == 'empty-trash') {
foreach ($storage_pool_drives as $sp_drive) {
$trash_path = clean_dir("$sp_drive/.gh_trash");
if (!file_exists($trash_path)) {
echo "Trash in $sp_drive is empty. Nothing to do.\n";
} else {
$trash_size = trim(exec("du -sk " . escapeshellarg($trash_path) . " | awk '{print $1}'"));
echo "Trash in $sp_drive is " . bytes_to_human($trash_size*1024, FALSE) . ". Emptying... ";
exec("rm -rf " . escapeshellarg($trash_path));
echo "Done\n";
}
}
if (isset($trash_share) && mb_strlen(escapeshellarg($trash_share['landing_zone'])) > 8) {
exec("rm -rf " . escapeshellarg($trash_share['landing_zone']) . '/*');
}
exit(0);
}
if ($action == 'view-queue') {
$shares_names = array_keys($shares_options);
natcasesort($shares_names);
$max_share_strlen = max(array_merge(array_map('mb_strlen', $shares_names), array(7)));
$queues = array();
$total_num_writes_pending = $total_num_delete_pending = $total_num_rename_pending = $total_num_fsck_pending = 0;
foreach ($shares_names as $share_name) {
$result = db_query(sprintf("SELECT COUNT(*) AS num FROM tasks WHERE action = 'write' AND share = '%s' AND complete IN ('yes', 'thawed')", db_escape_string($share_name))) or die("Can't find # of writes in tasks table: " . db_error());
$row = db_fetch_object($result);
$num_writes_pending = (int) $row->num;
$total_num_writes_pending += $num_writes_pending;
$result = db_query(sprintf("SELECT COUNT(*) AS num FROM tasks WHERE (action = 'unlink' OR action = 'rmdir') AND share = '%s' AND complete IN ('yes', 'thawed')", db_escape_string($share_name))) or die("Can't find # of deletes in tasks table: " . db_error());
$row = db_fetch_object($result);
$num_delete_pending = (int) $row->num;
$total_num_delete_pending += $num_delete_pending;
$result = db_query(sprintf("SELECT COUNT(*) AS num FROM tasks WHERE action = 'rename' AND share = '%s' AND complete IN ('yes', 'thawed')", db_escape_string($share_name))) or die("Can't find # of renames in tasks table: " . db_error());
$row = db_fetch_object($result);
$num_rename_pending = (int) $row->num;
$total_num_rename_pending += $num_rename_pending;
$result = db_query(sprintf("SELECT COUNT(*) AS num FROM tasks WHERE (action = 'fsck' OR action = 'fsck_file' OR action = 'md5') AND share = '%s'", db_escape_string($share_name))) or die("Can't find # of fsck in tasks table: " . db_error());
$row = db_fetch_object($result);
$num_fsck_pending = (int) $row->num;
$landing_zone = $shares_options[$share_name]['landing_zone'];
$result = db_query(sprintf("SELECT COUNT(*) AS num FROM tasks WHERE (action = 'fsck' OR action = 'fsck_file' OR action = 'md5') AND share LIKE '%s/%%'", db_escape_string($landing_zone))) or die("Can't find # of fsck in tasks table: " . db_error());
$row = db_fetch_object($result);
$num_fsck_pending += (int) $row->num;
$total_num_fsck_pending += $num_fsck_pending;
$queues[$share_name] = (object) array(
'num_writes_pending' => $num_writes_pending,
'num_delete_pending' => $num_delete_pending,
'num_rename_pending' => $num_rename_pending,
'num_fsck_pending' => $num_fsck_pending,
);
}
$queues['Total'] = (object) array(
'num_writes_pending' => $total_num_writes_pending,
'num_delete_pending' => $total_num_delete_pending,
'num_rename_pending' => $total_num_rename_pending,
'num_fsck_pending' => $total_num_fsck_pending,
);
$queues['Spooled'] = (int) exec("find -L /var/spool/greyhole -type f | wc -l");
if (isset($options['json'])) {
echo json_encode($queues);
} else {
echo "\nGreyhole Work Queue Statistics\n==============================\n\n";
echo "This table gives you the number of pending operations queued for the Greyhole daemon, per share.\n\n";
$col_size = 7;
foreach ($queues['Total'] as $type => $num) {
$num = number_format($num, 0);
if (strlen($num) > $col_size) {
$col_size = strlen($num);
}
}
$col_format = '%' . $col_size . 's';
printf("%$max_share_strlen"."s $col_format $col_format $col_format $col_format\n", '', 'Write', 'Delete', 'Rename', 'Check');
foreach ($queues as $share_name => $queue) {
if ($share_name == 'Spooled') continue;
if ($share_name == 'Total') {
for ($i=0; $i<$max_share_strlen+2+(4*$col_size)+(3*2); $i++) {
echo "=";
}
echo "\n";
}
echo sprintf("%-$max_share_strlen"."s", $share_name) . " ";
echo sprintf($col_format, number_format($queue->num_writes_pending, 0)) . " ";
echo sprintf($col_format, number_format($queue->num_delete_pending, 0)) . " ";
echo sprintf($col_format, number_format($queue->num_rename_pending, 0)) . " ";
echo sprintf($col_format, number_format($queue->num_fsck_pending, 0)) . "\n";
}
printf("%$max_share_strlen"."s $col_format $col_format $col_format $col_format\n", '', 'Write', 'Delete', 'Rename', 'Check');
echo "\nThe following is the number of pending operations that the Greyhole daemon still needs to parse.\n";
echo "Until it does, the nature of those operations is unknown.\n";
echo "Spooled operations that have been parsed will be listed above and disappear from the count below.\n";
echo sprintf("\n%-$max_share_strlen"."s ", 'Spooled');
echo number_format($queues['Spooled'], 0) . "\n";
echo "\n";
}
exit(0);
}
if ($action == 'status') {
$num_dproc = (int) exec('ps ax | grep "greyhole --daemon\|greyhole -D" | grep -v grep | wc -l');
if ($num_dproc == 0) {
echo "\nGreyhole daemon is currently stopped.\n\n";
exit(1);
}
$task = get_next_task($temp_rs, TRUE);
if ($task === FALSE) {
echo "\nCurrently idle.\n";
} else {
echo "\nCurrently working on task ID $task->id: $task->action " . clean_dir("$task->share/$task->full_path") . ($task->action == 'rename' ? " -> " . clean_dir("$task->share/$task->additional_info") : '') . "\n";
}
exec("tail -10 " . escapeshellarg($greyhole_log_file), $last_log_lines);
echo "\nRecent log entries:\n";
echo " " . implode("\n ", $last_log_lines) . "\n";
$last_log_line = $last_log_lines[count($last_log_lines)-1];
$last_action_time = strtotime(mb_substr($last_log_line, 0, 15));
$raw_last_log_line = mb_substr($last_log_line, 16);
$last_log_line = explode(' ', $raw_last_log_line);
$last_action = str_replace(':', '', $last_log_line[1]);
echo "\nLast logged action: $last_action\n";
echo " on " . date('Y-m-d H:i:s', $last_action_time) . " (" . how_long_ago($last_action_time) . ")\n";
echo "\n";
exit(0);
}
if ($action == 'stats') {
if (file_exists('/sbin/zpool')) {
if (exec("whoami") != 'root') {
echo "Warning: If you are using ZFS datasets as Greyhole storage pool drives, you will need to execute this as root.\n";
}
}
$max_drive_strlen = max(array_map('mb_strlen', $storage_pool_drives)) + 1;
$totals = array(
'total_space' => 0,
'used_space' => 0,
'free_space' => 0,
'trash_size' => 0,
'potential_available_space' => 0
);
$dfs = get_free_space_in_storage_pool_drives();
$stats = array();
foreach ($storage_pool_drives as $sp_drive) {
if (!isset($dfs[$sp_drive]) || !file_exists($sp_drive)) {
$stats[$sp_drive] = (object) array();
continue;
}
if (!is_greyhole_owned_drive($sp_drive)) {
$stats[$sp_drive] = (object) array();
continue;
}
$df_command = "df -k " . escapeshellarg($sp_drive) . " | tail -1";
unset($responses);
exec($df_command, $responses);
$total_space = 0;
$used_space = 0;
if (isset($responses[0])) {
if (preg_match("@\s+([0-9]+)\s+([0-9]+)\s+[0-9]+\s+[0-9]+%\s+.+$@", $responses[0], $regs)) {
$total_space = (float) $regs[1];
$used_space = (float) $regs[2];
}
}
$free_space = $dfs[$sp_drive]['free'];
$trash_path = clean_dir("$sp_drive/.gh_trash");
if (!file_exists($trash_path)) {
$trash_size = (float) 0;
} else {
$trash_size = (float) trim(exec("du -sk " . escapeshellarg($trash_path) . " | awk '{print $1}'"));
}
$potential_available_space = (float) $free_space + $trash_size;
$stats[$sp_drive] = (object) array(
'total_space' => $total_space,
'used_space' => $used_space,
'free_space' => $free_space,
'trash_size' => $trash_size,
'potential_available_space' => $potential_available_space,
);
$totals['total_space'] += $total_space;
$totals['used_space'] += $used_space;
$totals['free_space'] += $free_space;
$totals['trash_size'] += $trash_size;
$totals['potential_available_space'] += $potential_available_space;
}
$stats['Total'] = (object) $totals;
if (isset($options['json'])) {
echo json_encode($stats);
} else {
echo "\nGreyhole Statistics\n===================\n\n";
echo "Storage Pool\n";
printf("%$max_drive_strlen"."s Total - Used = Free + Trash = Possible\n", '');
foreach ($stats as $sp_drive => $stat) {
if ($sp_drive == 'Total') printf(" %-$max_drive_strlen"."s ==========================================\n", "");
printf(" %-$max_drive_strlen"."s ", "$sp_drive:");
if (empty($stat->total_space)) {
echo " Offline \n";
} else {
echo sprintf('%5.0f', $stat->total_space/1024/1024) . "G - " . sprintf('%5.0f', $stat->used_space/1024/1024) . "G = " . sprintf('%5.0f', $stat->free_space/1024/1024) . "G + " . sprintf('%5.0f', $stat->trash_size/1024/1024) . "G = " . sprintf('%5.0f', $stat->potential_available_space/1024/1024) . "G\n";
}
}
echo "\n";
}
exit(0);
}
if ($action == 'replace') {
if (array_search(@$options['drive'], $storage_pool_drives) === FALSE) {
$options['drive'] = '/' . trim(@$options['drive'], '/');
}
if (array_search($options['drive'], $storage_pool_drives) === FALSE) {
if (!empty($options['drive'])) {
echo "Drive " . $options['drive'] . " is not one of your defined storage pool drive.\n";
}
echo "Please use one of the following with the --replace option:\n ";
echo implode("\n ", $storage_pool_drives) . "\n";
echo "Note that the correct syntax for this command is:\n";
echo " greyhole --$action=<drive>\n";
echo "The '=' character is mandatory.\n";
exit(1);
}
if (!is_dir($options['drive'])) {
gh_log(ERROR, "The directory " . $options['drive'] . " does not exists. Greyhole can't --replace directories that don't exits.");
echo "The directory " . $options['drive'] . " does not exists. Greyhole can't --replace directories that don't exits.\n";
exit(2);
}
remove_drive_definition($options['drive']);
gh_log(INFO, "Storage pool drive " . $options['drive'] . " has been marked replaced. The Greyhole daemon will now be restarted to allow it to use this new drive.");
echo "Storage pool drive " . $options['drive'] . " has been marked replaced. The Greyhole daemon will now be restarted to allow it to use this new drive.\n";
restart_service();
exit(0);
}
if ($action == 'wait-for') {
if (!mark_gone_ok($options['drive'])) {
if (!empty($options['drive'])) {
echo "Drive " . $options['drive'] . " is not one of your defined storage pool drive.\n";
}
echo "Please use one of the following with the --wait-for option:\n ";
echo implode("\n ", $storage_pool_drives) . "\n";
echo "Note that the correct syntax for this command is:\n";
echo " greyhole --$action=<drive>\n";
echo "The '=' character is mandatory.\n";
exit(1);
}
gh_log(INFO, "Storage pool drive " . $options['drive'] . " has been marked Temporarily-Gone");
echo "Storage pool drive " . $options['drive'] . " has been marked Temporarily-Gone, which means the missing file copies that are in this drive will not be re-created until it reappears.\n";
exit(0);
}
if ($action == 'balance') {
$query = "INSERT INTO tasks (action, share, complete) VALUES ('balance', '', 'yes')";
db_query($query) or gh_log(CRITICAL, "Can't insert balance task: " . db_error());
echo "A balance has been scheduled. It will start after all currently pending tasks have been completed.\n";
echo "This operation will try to even the available space on all drives included in your storage pool.\n";
exit(0);
}
if ($action == 'cancel-balance') {
db_query("DELETE FROM tasks WHERE action = 'balance'") or gh_log(CRITICAL, "Can't delete balance tasks: " . db_error());
echo "All scheduled balance tasks have now been deleted.\n";
restart_service();
exit(0);
}
if ($action == 'cancel-fsck') {
db_query("DELETE FROM tasks WHERE action = 'fsck'") or gh_log(CRITICAL, "Can't delete fsck tasks: " . db_error());
db_query("DELETE FROM tasks WHERE action = 'md5'") or gh_log(CRITICAL, "Can't delete md5 tasks: " . db_error());
echo "All scheduled fsck tasks have now been deleted.\n";
echo "Specific files checks might have been queued for problematic files, and those (fsck_file) tasks will still be executed, once other tasks have been processed.\n";
restart_service();
exit(0);
}
if ($action == 'fsck') {
$pos = array_search('fsck', $argv);
$full_path = '';
if (isset($options['dir'])) {
$full_path = $options['dir'];
if (!is_dir($full_path)) {
echo "$full_path is not a directory. Exiting.\n";
exit(1);
}
}
$fsck_options = array();
if (isset($options['email-report'])) {
$fsck_options[] = 'email';
}
if (!isset($options['dont-walk-metadata-store'])) {
$fsck_options[] = 'metastore';
}
if (isset($options['if-conf-changed'])) {
$fsck_options[] = 'if-conf-changed';
}
if (isset($options['find-orphaned-files'])) {
$fsck_options[] = 'orphaned';
}
if (isset($options['checksums'])) {
$fsck_options[] = 'checksums';
}
if (isset($options['delete-orphaned-metadata'])) {
$fsck_options[] = 'del-orphaned-metadata';
}
if ($full_path == '') {
schedule_fsck_all_shares($fsck_options);
$full_path = 'all shares';
} else {
$query = sprintf("INSERT INTO tasks (action, share, additional_info, complete) VALUES ('fsck', '%s', %s, 'yes')",
db_escape_string($full_path),
(!empty($fsck_options) ? "'" . implode('|', $fsck_options) . "'" : "NULL")
);
db_query($query) or gh_log(CRITICAL, "Can't insert fsck task: " . db_error());
}
echo "fsck of $full_path has been scheduled. It will start after all currently pending tasks have been completed.\n";
if (isset($options['checksums'])) {
echo "Any mismatch in checksums will be logged in both " . $greyhole_log_file . " and " . FSCKLogFile::PATH . "/fsck_checksums.log\n";
}
// Also clean the tasks_completed table
delete_executed_tasks();
exit(0);
}
if ($action == 'md5-worker') {
if (is_array($options['drive'])) {
$drives = $options['drive'];
} else {
$drives = array($options['drive']);
}
md5_worker_thread($drives);
exit(0);
}
$num_daemon_processes = exec('ps ax | grep "greyhole --daemon\|greyhole -D" | grep -v grep | wc -l');
if ($num_daemon_processes > 1) {
die("Found an already running Greyhole daemon with PID " . trim(file_get_contents('/var/run/greyhole.pid')) . ".\nCan't start multiple Greyhole daemons.\nQuitting.\n");
}
gh_log(INFO, "Greyhole (version %VERSION%) daemon started.");
repair_tables();
set_uniq_id();
terminology_conversion();
set_metastore_backup();
Settings::backup();
samba_check_vfs();
parse_samba_spool();
simplify_tasks();
while (TRUE) {
parse_samba_spool();
$action = 'check_pool';
check_storage_pool_drives();
execute_next_task();
}
function terminology_conversion() {
convert_folders('.gh_graveyard','.gh_metastore');
convert_folders('.gh_graveyard_backup','.gh_metastore_backup');
convert_folders('.gh_attic','.gh_trash');
convert_database();
convert_sp_drives_tag_files();
}
function convert_sp_drives_tag_files() {
global $storage_pool_drives, $going_drive, $allow_multiple_sp_per_device;
$drives_definitions = Settings::get('sp_drives_definitions', TRUE);
if (!$drives_definitions) {
$drives_definitions = array();
}
foreach ($storage_pool_drives as $sp_drive) {
if (isset($going_drive) && $sp_drive == $going_drive) { continue; }
$drive_uuid = gh_dir_uuid($sp_drive);
if (!isset($drives_definitions[$sp_drive])) {
if (is_dir($sp_drive)) {
$drives_definitions[$sp_drive] = $drive_uuid;
}
}
if (!isset($drives_definitions[$sp_drive])) {
continue;
}
if ($drives_definitions[$sp_drive] === FALSE) {
unset($drives_definitions[$sp_drive]);
continue;
}
if (file_exists("$sp_drive/.greyhole_uses_this") && $drive_uuid != 'remote') {
unlink("$sp_drive/.greyhole_uses_this");
}
if ($drives_definitions[$sp_drive] != $drive_uuid) {
gh_log(WARN, "Warning! It seems the partition UUID of $sp_drive 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.");
}
}
foreach ($drives_definitions as $sp_drive => $uuid) {
if (array_search($sp_drive, $storage_pool_drives) === FALSE) {
unset($drives_definitions[$sp_drive]);
}
}
// Check that the user is not using two sp drives on the same device
$devices = array();
foreach ($drives_definitions as $sp_drive => $device_id) {
$devices[$device_id][] = $sp_drive;
}
foreach ($devices as $device_id => $sp_drives) {
if (count($sp_drives) > 1 && $device_id !== 0 && $device_id != 'remote') {
if ($allow_multiple_sp_per_device) {
gh_log(INFO, "The following storage pool drives are on the same partition: " . implode(", ", $sp_drives) . ", but per greyhole.conf 'allow_multiple_sp_per_device' options, you chose to ignore this normally critical error.");
} else {
gh_log(CRITICAL, "ERROR: The following storage pool drives are on the same partition: " . implode(", ", $sp_drives) . ". The Greyhole daemon will now stop.");
}
}
}
Settings::set('sp_drives_definitions', $drives_definitions);
return $drives_definitions;
}
function convert_database() {
Settings::rename('graveyard_backup_directory', 'metastore_backup_directory');
$setting = Settings::get('metastore_backup_directory', FALSE, '%graveyard%');
if ($setting) {
$new_value = str_replace('/.gh_graveyard_backup', '/.gh_metastore_backup', $setting);
Settings::set('metastore_backup_directory', $new_value);
}
}
function convert_folders($old,$new) {
global $storage_pool_drives;
foreach ($storage_pool_drives as $sp_drive) {
$old_term = clean_dir("$sp_drive/".$old);
$new_term = clean_dir("$sp_drive/".$new);
if (file_exists($old_term)) {
gh_log(INFO, "Moving $old_term to $new_term...");
gh_rename($old_term,$new_term);
}
}
}
function get_next_task(&$result_new_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";
$result_new_tasks = db_query($query) or gh_log(CRITICAL, "Can't query tasks: " . db_error());
$task = db_fetch_object($result_new_tasks);
if ($task === 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_query($query) or gh_log(CRITICAL, "Can't update idle tasks to complete tasks: " . db_error());
$task = get_next_task($result_new_tasks, $incl_md5, FALSE);
}
return $task;
}
function execute_next_task() {
global $log_level, $fsck_report, $storage_pool_drives, $shares_options, $email_to, $sleep_before_task, $action, $frozen_directories, $next_task, $current_task_id, $locked_files, $result_new_tasks, $fix_symlinks_scanned_dirs;
if (isset($next_task)) {
$task = $next_task;
unset($GLOBALS['next_task']);
} else {
$task = FALSE;
if (!empty($result_new_tasks)) {
$task = db_fetch_object($result_new_tasks);
if ($task === FALSE) {
db_free_result($result_new_tasks);
$result_new_tasks = null;
}
}
if ($task === FALSE) {
$task = get_next_task($result_new_tasks, TRUE);
if ($task === FALSE) {
$action = 'sleep';
gh_log(DEBUG, "Nothing to do... Sleeping.");