forked from KlausKnopper/cloop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
advfs.cc
1267 lines (1070 loc) · 37 KB
/
advfs.cc
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
/* Creates a compressed image, given a file as an argument.
* (c)1999 Paul `Rusty' Russell. GPL.
*
* CHANGELOG:
*
* * Wed, 02 Aug 2006 02:01:42 +0200 Eduard Bloch <[email protected]>
* - cleanup, fixed memory leak in doLocalCompression with best compression
* - simplified the control flow a lot, it was overdesigned. Kept one ring
* buffer for data passing and aside buffers for temp. data storage.
*
* * Mon, 29 Aug 2005 15:20:10 CEST 2005 Eduard Bloch <[email protected]>
* - a complete overhaul, rewrote most parts using STL and C++ features,
* portable data types etc.pp.
* - using multiple threads, input/output buffers, various strategies for
* temporary data storage, options parsing with getopt, and: network enabled
* server/client modes, distributing the compression jobs to many nodes
*
* * Mon Feb 28 20:45:14 CET 2005 Sebastian Schmidt <[email protected]>
* - Added -t command line option to use a temporary file for the compressed
* blocks instead of saving it in cb_list.
* - Added information message before the write of the compressed image.
* * Sat Deb 14 22:49:20 CEST 2004 Christian Leber
* - Changed to work with the advancecomp packages, so that it's
* better algorithms may be used
* * Sun Okt 26 01:05:29 CEST 2003 Klaus Knopper
* - Changed format of index pointers to network byte order
* * Sat Sep 29 2001 Klaus Knopper <[email protected]>
* - changed compression to Z_BEST_COMPRESSION,
* * Sat Jun 17 2000 Klaus Knopper <[email protected]>
* - Support for reading file from stdin,
* - Changed Preamble.
* * Sat Jul 28 2001 Klaus Knopper <[email protected]>
* - cleanup and gcc 2.96 / glibc checking
*/
#define _FILE_OFFSET_BITS 64
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <pthread.h>
#include <time.h>
#include <endian.h>
#include <fcntl.h>
#include <zlib.h>
#include "cloop.h"
#include "portable.h"
#include "pngex.h"
//#include "utility.h"
#include "compress.h"
#include "siglock.h"
#ifndef __OPTIMIZE__
#define __OPTIMIZE__
#endif
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#if defined(__linux__)
#include <sys/socketvar.h>
#endif
#include "lib/mng.h"
#include "lib/endianrw.h"
// for server
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <list>
#include <map>
#include <vector>
#include <limits>
using namespace std;
#define DEBUG(x)
//#define DEBUG(x) cerr << x << endl;
//#define MAX_KMALLOC_SIZE 2L<<17
#define CLOOP_PREAMBLE "#!/bin/sh\n" "#V2.0 Format\n" "modprobe cloop file=$0 && mount -r -t iso9660 /dev/cloop $1\n" "exit $?\n"
#define MAXLEN(bs) ((bs) + (bs)/1000 + 12)
int maxlen(0);
#ifdef __CYGWIN__
typedef uint64_t loff_t;
#endif
# if defined(linux) || defined(__linux__)
#include <asm/byteorder.h>
#define ENSURE64UINT(x) __cpu_to_be64(x)
#else // not linux
#ifndef be64toh
#if BYTE_ORDER == LITTLE_ENDIAN
static __inline __uint64_t
__bswap64(__uint64_t _x)
{
return ((_x >> 56) | ((_x >> 40) & 0xff00) | ((_x >> 24) & 0xff0000) |
((_x >> 8) & 0xff000000) | ((_x << 8) & ((__uint64_t)0xff << 32)) |
((_x << 24) & ((__uint64_t)0xff << 40)) |
((_x << 40) & ((__uint64_t)0xff << 48)) | ((_x << 56)));
}
#define be64toh(x) __bswap64(x)
#else // BIG ENDIAN
#define be64toh(x) x
#endif
#endif /* !be64toh */
#define ENSURE64UINT be64toh
#endif // linux
#define die(msg) { cerr << "ERROR: " << msg << ". Exiting..."<<endl; exit(1); }
#ifndef MSG_WAITALL
#define MSG_WAITALL 0
#endif
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
// some globals, easier option passing
int defport=3103;
int ret=0;
unsigned long blocksize=0;
unsigned long expected_blocks=0;
//unsigned long numblocks=0;
int method=Z_BEST_COMPRESSION;
const int maxalg=11;
unsigned int levelcount[maxalg];
bool be_verbose(false), be_quiet(false);
#define TOFILE 0
#define TOTEMPFILE 1
#define TOMEM 2
int targetkind(TOFILE);
FILE *targetfh(NULL), *datafh(NULL), *tempfh(NULL);
bool reuse_as_tempfile(false);
int workThreads=3;
vector<char *> hostpool;
vector<uint64_t> lengths;
vector<char *> blocks;
pthread_mutex_t mainlock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t maincond = PTHREAD_COND_INITIALIZER;
#define lock pthread_mutex_lock( &mainlock )
#define unlock pthread_mutex_unlock( &mainlock )
#define doSleep pthread_cond_wait(&maincond, &mainlock)
#define doAwake pthread_cond_broadcast(&maincond)
class compressItem;
compressItem *pool;
int poolsize(0);
int posAdd(0);
int posFetch(0);
bool terminateAll=false;
// job size
unsigned long jobsize = 32;
int in(-1);
int start_server(int port);
int setup_connection(char *peer);
/* cludge
FILE * split_fopen( char *path, char *mode);
int split_fwrite(void *ptr, size_t nmemb);
uint64_t chunk_size=0;
*/
class compressItem {
public:
// those are the only interesting unique attributes
int best;
unsigned long compLen;
#define STOPMARK -2
#define SDIRTY -1
#define SFRESH 0
#define SRESERVED 1
#define SCOMPRESSED 2
int state;
char *inBuf, *outBuf;
compressItem() : state(SDIRTY) {
maxlen=MAXLEN(blocksize); // is global, though
inBuf =(char *) malloc(blocksize);
outBuf=(char *) malloc(maxlen);
};
void set_size (int id, int size)
{
//uncompLen=size;
// if incomplete, add padding
};
~compressItem() { // don't care, cleared at app exit
// deleted by compress methods or by others
//if(uncompBuf) delete[] uncompBuf;
//if(compBuf) delete[] compBuf;
}
bool doRemoteCompression(int method, int con) {
DEBUG("sending data");
if(send(con, inBuf, blocksize, MSG_NOSIGNAL) == -1) {
DEBUG("data sending failed");
return false;
}
DEBUG("awaiting compressed data, should come back before TCP timeouts");
uint32_t rhead[2];
int l=recv(con, rhead, sizeof(rhead), MSG_WAITALL | MSG_NOSIGNAL);
if(l<1) return false;
compLen=ntohl(rhead[0]);
best=ntohl(rhead[1]);
DEBUG("Receiving: " << compLen << " bytes\n");
// Cygwin does not know MSG_WAITALL and splits large blobs :(
char * ptr = outBuf;
int rest = compLen;
while(rest>0) {
l=recv(con, ptr, rest, MSG_WAITALL | MSG_NOSIGNAL);
if(l<1) return false;
ptr+=l;
rest-=l;
}
DEBUG("### Received\n");
return true;
}
bool doLocalCompression(int method=0) {
const int maxalg=11;
int z_error;
if(method >= 0)
{
compLen=maxlen;
best=method;
z_error=compress2((Bytef*) outBuf, (uLongf*) & compLen, (Bytef*)inBuf, blocksize, method);
if(z_error != Z_OK)
{
cerr << "**** Error " << z_error << " compressing block" << endl;
return false;
}
}
else if(method==-1) {
compLen=maxlen;
best=10;
unsigned int tmp=compLen; // stupid, but needed on 64bit...
if(!compress_zlib(shrink_extreme, (unsigned char *) outBuf, tmp, (unsigned char *)inBuf, blocksize))
{
fprintf(stderr, "*** Error compressing block with 7ZIP!\n");
return false;
}
compLen=tmp;
}
else if(method<-1)
{
compLen=maxlen+1; // first one should win in the beginning
char *tmpBuf=(char *) malloc(maxlen);
unsigned long tmpLen=maxlen;
if(!tmpBuf)
die("Out of Memory.");
//int j=(method<-2)?9:0;
for(int j=0; j<maxalg; j++) {
tmpLen = maxlen;
// DEBUG
// fprintf(stderr, " trying: %2d\r", j); fflush(stderr);
if(j<10) {
if((z_error=compress2((Bytef*)tmpBuf, (uLongf*)&tmpLen, (Bytef*)inBuf, blocksize, j)) != Z_OK)
{
fprintf(stderr, "*** Error %d compressing block, algo: %d!\n", z_error, j);
return false;
}
}
else { // try 7zip as the last one
unsigned int tmp=tmpLen; // stupid, but needed on 64bit...
if(!compress_zlib(shrink_extreme, (unsigned char *) tmpBuf, tmp, (unsigned char *)inBuf, blocksize))
{
fprintf(stderr, "*** Error %d compressing block with 7ZIP!\n", j);
return false;
}
tmpLen=tmp;
}
if(tmpLen<compLen) { // a new winner found, swap tmpBuf and compLen
best=j;
compLen=tmpLen;
char *t = tmpBuf;
tmpBuf=outBuf;
outBuf=t;
}
}
free(tmpBuf);
}
DEBUG("done");
return true;
}
};
void *compressingLoop(void *ptr)
{
int id = * ( (int*) ptr);
DEBUG("Worker Nr. " << id << " created");
char *peer;
int con=-1;
if(hostpool.size()) {
peer = hostpool[id % hostpool.size()];
if(strcmp(peer, "LOCAL")) {
con=setup_connection(peer);
if(con<0)
cerr << "Unable to connect, compressing locally\n";
}
// otherwise compress locally
}
int pos(0);
while(!terminateAll)
{
#if 1
DEBUG("c1");
lock;
get_fresh_stuff:
DEBUG("c2");
int i=1;
for(;i<=poolsize;i++) {
int j=(pos+i)%poolsize;
if(pool[j].state==SFRESH) { // MINE!
pool[j].state=SRESERVED;
pos=j;
break;
}
}
DEBUG("c3, i: "<<i);
if(i>poolsize) { doSleep; goto get_fresh_stuff; }
DEBUG("c4");
unlock;
#else
// simplier/stupid version, just pickup the first one
lock;
get_fresh_stuff:
for(pos=0;pos<poolsize;pos++) {
if(pool[pos].state==SFRESH) { // MINE!
pool[pos].state=SRESERVED;
break;
}
}
if(pos==poolsize) { doSleep; goto get_fresh_stuff; }
unlock;
#endif
do_local:
if(con<0) {
DEBUG("c5");
if (! pool[pos].doLocalCompression(method) )
die("Compression failed on block " <<pos);
}
else {
DEBUG("c6");
if(! pool[pos].doRemoteCompression(method, con) )
{
con=-1;
cerr << "Remote compression failed, doing local now...\n";
goto do_local;
}
}
DEBUG("Calc: submitting results of pos: " << pos);
DEBUG("c7");
lock;
pool[pos].state=SCOMPRESSED;
doAwake;
unlock;
DEBUG("c8");
}
return(NULL); // g++ shut up
}
void *outputFetch(void *ptr) {
//int id = * ( (int*) ptr);
DEBUG("Fetcher thread created");
uint64_t total_compressed(0);
for(int i=0; i<maxalg; i++) levelcount[i]=0; // or better with memset?
time_t starttime=time(NULL);
DEBUG("f1");
while(true) {
int pos=posFetch%poolsize;
DEBUG("f2");
lock;
DEBUG("f3");
while(/*posFetch<=posAdd || */pool[pos].state!=SCOMPRESSED) {
DEBUG("f4, pos: "<<pos);
if(pool[pos].state==STOPMARK) // ugly, exiting program with hot locks... don't care
return(NULL);
DEBUG("f4.1");
doSleep;
DEBUG("f4.2");
}
unlock;
DEBUG("f5");
total_compressed += pool[pos].compLen;
++levelcount[pool[pos].best];
lengths.push_back(pool[pos].compLen); // could seek, but that may be faster after all
DEBUG("f6, target: " << targetkind);
if(targetkind<TOMEM)
{
DEBUG("f6.5");
if(pool[pos].compLen != fwrite(pool[pos].outBuf, sizeof(char), pool[pos].compLen, datafh))
die("Writting output");
}
else { //TOMEM
char *t=(char *) malloc(pool[pos].compLen);
if(!t) {
cerr << "Virtual memory exhausted. Use temp. file mode or add more swap." <<endl;
exit(1);
}
memcpy(t, pool[pos].outBuf, pool[pos].compLen);
blocks.push_back(t);
}
DEBUG("f7");
/* Print status */
if(be_verbose || 0==posFetch%100 || posFetch==(int)expected_blocks-1) {
unsigned int per=1+time(NULL)-starttime;
fprintf(stderr,
"[%2d] Blk# %5d, [ratio/avg. %3d%%/%3d%%], avg.speed: %d b/s, ETA: %ds\n",
pool[pos].best,
posFetch,
(int)(((float)pool[pos].compLen*(float)100) / (float)blocksize ),
(int)(((float) total_compressed*100) / (((float)posFetch+1)*(float)blocksize)),
((posFetch+1)*blocksize)/per,
( per*(expected_blocks-posFetch-1) ) / (posFetch+1)
);
#if 0
fprintf(stderr,
"[%2d] Blk# %5d, [ratio%3lu%%, avg.%3lu%%], avg.speed: %d b/s, ETA: %ds\n",
pool[pos].best,
posFetch,
(pool[pos].compLen*100) / blocksize,
(total_compressed*100) / ((posFetch+1)*blocksize),
((posFetch+1)*blocksize)/per,
( per*(expected_blocks-posFetch-1) ) / (posFetch+1)
);
#endif
}
lock;
pool[pos].state=SDIRTY;
posFetch++;
doAwake;
unlock;
}
return(NULL);
}
void *inputFeed(void *ptr) {
//int id = * ( (int*) ptr);
DEBUG("Input thread created");
compressItem *item;
int newstate(SFRESH);
bool finishing(false);
while(true) {
DEBUG("s1");
int pos=posAdd%poolsize ;
DEBUG("s3");
lock;
DEBUG("s4");
while(pool[pos].state!=SDIRTY) // overrun? wait for outputFetch to mark it dirty again
doSleep;
DEBUG("s5");
// not changing posAdd yet, keep it dirty
unlock;
DEBUG("Next block...");
if(finishing)
newstate=STOPMARK;
else {
char *ptr=pool[pos].inBuf;
size_t rest=blocksize;
while(rest>0) {
ssize_t r=read(in, ptr, rest);
if(r<0)
die("Input stream error");
ptr+=r;
rest-=r;
if(!r)
break;
}
DEBUG("Block rest: " << rest);
if(rest==blocksize) { // zero read, previous block was the last one
DEBUG("s2.3");
newstate=STOPMARK;
}
else if(posAdd==expected_blocks) { // got data but this block is already one too much, ignore it and bail out
DEBUG("s2.2");
ret=1;
cerr << "WARNING: got more data than expected. Trailing data is ignored, your image may be incomplete." <<endl;
newstate=STOPMARK;
}
if(rest>0) // padding with zeroes and making sure that the endmark will be set in the next block
{
memset(ptr, 0, rest);
finishing=true;
}
}
lock;
DEBUG("Set new state on " << posAdd << ", " << newstate);
pool[pos].state=newstate;
posAdd++;
doAwake; // go compressors, go
unlock;
if(newstate==STOPMARK) {
DEBUG("Set stop mark on " << posAdd-1);
return(NULL);
}
}
return(NULL);
}
int create_compressed_blocks_mt() {
int threadId=0;
pthread_t output_thread;
#if 0
if(hostpool.size()) {
int n=0;
for(int sid=0; sid < workThreads ; sid++) {
try_another_connection:
char *peer = hostpool[n++ % hostpool.size()];
int con=-1;
con=setup_connection(peer);
if(con<0) {
cerr << "Connection to " <<peer <<" failed. Wrong port?"<<endl;
if(n>sid+5) die("Too many connection failures on ");
goto try_another_connection;
}
DEBUG("got con: " << con << " for " <<sid);
conpool.push_back(con);
}
}
#endif
pool = new compressItem[workThreads+3];
for(; threadId < workThreads ; threadId++)
pthread_create(new pthread_t, NULL, compressingLoop, (void *) new int(threadId));
pthread_create(new pthread_t, NULL, inputFeed, (void *) new int(threadId++));
pthread_create(&output_thread, NULL, outputFetch, (void *) new int(threadId));
int ret;
pthread_join(output_thread, (void **) &ret);
DEBUG("or: " << ret);
terminateAll=true;
if(!be_quiet) {
fprintf(stderr,"\nStatistics:\n");
for(int j=0; j<maxalg-1; j++)
fprintf(stderr,"gzip(%d): %5d (%5.2g%%)\n",
j,
levelcount[j],
100.0F*(float)levelcount[j]/(float)lengths.size());
fprintf(stderr,"7zip: %5d (%5.2g%%)\n",
levelcount[10],
100.0F*(float)levelcount[10]/(float)lengths.size());
}
return ret;
};
#define OPTIONS "bB:mrp:lt:hs:f:j:a:vqS:L:"
int usage(char *progname)
{
cout << "Usage: advfs [options] INFILE OUTFILE [HOSTS...]" << endl;
cout << "Options:" << endl;
cout << " -b Try all and choose the best compression method, see -L" << endl;
cout << " -B N Set the block size to N" << endl;
cout << " -m Use memory for temporary data storage (NOT recommended)" << endl;
cout << " -r Reuse output file as temporary file (NOT recommended)" << endl;
cout << " -p M Set a default value for port number to M" <<endl;
cout << " -l Listening mode (as remote node)" <<endl;
cout << " -t T Total number of compressing threads" <<endl;
cout << " -s Q Expect data with size Q from the input, see below" <<endl;
cout << " -f S Temporary file S (or see -r)"<<endl;
cout << " -q Don't print periodic status messages to the console" << endl;
cout << " -v Verbose mode, print extra statistics" <<endl;
cout << " -h Help of the program" << endl;
cout << " -S X Experimental option: store volume header in file X, see manpage" <<endl;
cout << "Performance tuning options:"<<endl;
//cout << " -j W Jobsize, number W of blocks passed to each working thread per call"<<endl;
cout << " -a U Job pool size (default: threadcount+3)" <<endl;
cout << " -L V Compression level (-2..9); 9: zlib's best (default setting), 0: none,\n"
" -1: 7zip, -2: do all and keep the best one" <<endl;
/*
* does not make sense, 7zip is about 10 times slower than all gzip methods together
* , -3: like -2 but trying\n"
" only gzip:9 and 7zip (faster and one of them mostly wins anyway)" << endl;
*/
cout <<endl;
cout << "To use standard input/output - can be used as INFILE/OUTFILE. However, this will\n"
"require additional memory (or diskspace) for data size calculation and header\n"
"update (after compression). Passing the INPUT data size with -s may help.\n";
cout << "The size numbers can be declared with a suffix which acts as multiplier\n"
"(K: KiB, k: KB, i: iso9660 block (2KiB); M: MiB; m: MB; G: GiB; g: GB)." <<endl;
return(1);
}
uint64_t getsize(char *text) {
if(!text) return 0;
int map[] = {'k', 1000, 'K', 1024, 'm', 1000000, 'M', 1048576,
'g', 1000000000, 'G', 1073741824, 'i', 2048, 0 };
char *mod = text + strlen(text)-1;
uint64_t fac=0;
if(*mod > 57) {
for(int i=0;map[i];i+=2)
if(map[i]==*mod)
fac=map[i+1];
if(!fac) die("Unknown factor " << mod << " or bad size " << text);
*mod=0x0;
}
else fac=1;
return fac*atoll(text);
}
inline bool is_pos_number(char *text) {
for(char *p=text;*p;p++)
if(!isdigit(*p))
return false;
return true;
}
int main(int argc, char **argv)
{
struct cloop_head head;
uint64_t bytes_so_far;
char *tempfile(NULL), *sepheader(NULL);
uint64_t datasize=0;
int c;
#ifdef _SC_NPROCESSORS_ONLN
workThreads=sysconf(_SC_NPROCESSORS_ONLN);
cerr << workThreads << " processor core(s) detected\n";
#endif
while (1)
{
int option_index = 0;
#ifdef HAVE_GETOPT_LONG
static struct option long_options[] =
{
{"best", 0, 0, 'b'},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, OPTIONS,
long_options, &option_index);
#else
c = getopt(argc, argv, OPTIONS);
#endif
if (c == -1)
break;
switch (c)
{
case 'B':
blocksize=getsize(optarg);
if(blocksize > 1<<20) {
blocksize = 1<<20;
cerr << "Block size is too big. Adjusting to " << blocksize<<endl;
}
if(blocksize < 512) {
blocksize = 512;
cerr << "Block size is too small. Adjusting to " << blocksize<<endl;
}
if(blocksize%512) {
blocksize = blocksize-blocksize%512;
cerr << "Block size not multiple of 512. Adjusting to " << blocksize << endl;
}
break;
case 'm':
targetkind=TOMEM;
break;
case 'b':
method=-2;
break;
case 'L':
method=getsize(optarg);
if(method<-2 || method > 9)
die("Invalid compression method");
break;
case 'f':
targetkind=TOTEMPFILE;
tempfile=optarg;
break;
case 'v':
be_verbose=true;
break;
case 'q':
be_quiet=true;
break;
case 'r':
reuse_as_tempfile=true;
break;
case 'S':
sepheader=optarg;
break;
case 's':
datasize=getsize(optarg);
break;
case 'a':
poolsize=getsize(optarg);
break;
case 'j':
jobsize=getsize(optarg);
break;
case 'p':
defport=getsize(optarg);
if(defport>65535) die("Invalid port");
break;
case 'l':
start_server(defport);
exit(0);
break;
case 't':
{
int nMaxThreads=getsize(optarg);
if(nMaxThreads)
workThreads=nMaxThreads;
else
cerr << "Bad thread count, using default (" << workThreads << ")"<<endl;
}
break;
default:
usage(argv[0]);
exit(1);
}
}
const char *fromfile=NULL, *tofile=NULL;
int test;
if(optind > argc-2) {
usage(argv[0]);
die("\nInfile and outfile must be specified");
}
while(optind!=argc) {
if( 0==hostpool.size() && is_pos_number(argv[optind]) )
{
int val=getsize(argv[optind]);
cerr << "Warning, number as file string found. Assuming old command syntax and\n"
"choosing compatible parameters (-m -B " << val <<"). See the usage info (-h)\n"
"for better/correct parameters."<<endl;
blocksize=val;
targetkind=TOMEM;
fromfile=tofile="-";
}
else if(!fromfile) fromfile=argv[optind];
else if(!tofile) tofile = argv[optind];
else hostpool.push_back(argv[optind]);
optind++;
}
// initializing and normalizing parameters
if(!blocksize) blocksize=65536;
if(!poolsize) poolsize=workThreads+3;
if(tempfile && targetkind==TOMEM) die("Either -r or -m is allowed");
if(reuse_as_tempfile && tempfile) die("outfile reuse with another tempfile does not make sense");
if(sepheader && (reuse_as_tempfile || targetkind!=TOFILE ))
die("Separate header file only with pure file output supported"); // writing twice? Later... or never
if(!tofile)
die("Unknown output file. Provide a path name or - for STDOUT");
if(!fromfile)
die("Unknown input file. Provide a path name or - for STDIN");
if(strcmp(tofile, "-")) {
truncate(tofile,0);
targetfh=fopen(tofile, "w+");
if(!targetfh)
die("Opening output file for writing");
}
else {
targetfh=stdout; // oh, that crap
if(!sepheader && targetkind==TOFILE)
die("Unrewindable output, choose the tempdata storage strategy.\nOne of: -m or -f <file> required, or -S for detached header");
}
if(strcmp(fromfile, "-")) {
struct stat buf;
if(!datasize) {
stat(fromfile, &buf);
datasize=buf.st_size;
}
if(datasize < 8000)
die("Unknown or suspicious input data size. Use -s to specify a real value");
in=open(fromfile, O_RDONLY | O_LARGEFILE);
}
else
{
in=fileno(stdin);
if(!datasize) {
if(sepheader)
cerr << "Storing volume header in " << sepheader << " and compressed data in " << tofile << ", don't forget to merge them in correct order.\n";
else if(targetkind==TOFILE)
die("\nUnknown input data size and no tempdata storage strategy has been choosen.\nOne of: -s, -m, -f or -r required");
}
}
if(in<0) die("Opening input");
expected_blocks=datasize/blocksize;
if(datasize%blocksize) expected_blocks++;
if(!expected_blocks) expected_blocks=std::numeric_limits<int>::max();
datafh=targetfh; // for now
if(tempfile) {
tempfh=fopen(tempfile, "w+");
if(!tempfh)
die("Opening temporary file");
datafh=tempfh;
}
// precalculate some values
// expected values including additional pointer to store the initial offset
bytes_so_far = sizeof(head) + sizeof(uint64_t) * (expected_blocks+1);
if(!be_quiet)
cerr << "Block size "<< blocksize << ", expected number of blocks: " << expected_blocks <<endl;
DEBUG("Expected data start position: " << bytes_so_far);
if(sepheader)
datafh=targetfh;
else if(targetkind==TOFILE && !reuse_as_tempfile)
fseeko(targetfh, bytes_so_far, SEEK_SET);
// GO, GO, GO
if(create_compressed_blocks_mt())
die("An error was detected while compressing, exiting...");
close(in);
fflush(datafh);
// in tempdata modes choose real values rather than guessed
int numblocks=expected_blocks;
if(targetkind) {
numblocks=lengths.size();
bytes_so_far = sizeof(head) + sizeof(uint64_t) * (1+lengths.size());
}
else if(numblocks != lengths.size())
die("Incorrect number of blocks detected, "<<numblocks << " vs. " << lengths.size());
// stretch the temp/target file, shifting data to make space for the header
if(reuse_as_tempfile) {
cerr << "Shifting data..."<<endl;
try {
int clen=blocksize*16;
int64_t opos = ftello(targetfh);
char *buf = new char[clen];
int64_t ipos=opos-clen;
while(ipos != -clen) { // condition met after a read from 0 happened
if(ipos<0) {
// last incomplete block, fix the offsets etc.
clen+=ipos;
ipos=0;
}
if(fseeko(targetfh, ipos, SEEK_SET) < 0) throw 42;
if(fread( buf, sizeof(char), clen, targetfh) != clen) throw 42;
fseeko(targetfh, ipos+bytes_so_far, SEEK_SET);
if(fwrite(buf, sizeof(char), clen, targetfh) != clen) throw 42;
ipos-=clen;
}
}
catch(...) { die("Rewritting file"); };
}
if(sepheader) {
fclose(targetfh);
targetfh=fopen(sepheader, "w");
if(!targetfh)
die("Error writting header file, " << sepheader);
}
// seek back
fseeko(targetfh, 0, SEEK_SET);
/* Update the head... */
memset(head.preamble, 0, sizeof(head.preamble));
memcpy(head.preamble, CLOOP_PREAMBLE, sizeof(CLOOP_PREAMBLE));
head.block_size = htonl(blocksize);
head.num_blocks = htonl(numblocks);
/* Write out head... */
fwrite(&head, sizeof(head), 1, targetfh);
if(!be_quiet) cerr << "Writing index for " << lengths.size() << " block(s)...\n";
/* Write offsets, then data */
// initial offset first
uint64_t tmp;
DEBUG("Initial offset: " << bytes_so_far << " at pos: " << ftello(targetfh));
tmp = ENSURE64UINT(bytes_so_far);
fwrite(&tmp, sizeof(tmp), 1, targetfh);
for(int i=0;i<lengths.size();i++) {
bytes_so_far += lengths[i];
tmp = ENSURE64UINT(bytes_so_far);
if(1!=fwrite(&tmp, sizeof(tmp), 1, targetfh))
die("Unable to write to index area");
}
DEBUG("Writting data at pos: " << ftello(targetfh));
if(!be_quiet) cerr << "Writing compressed data...\n";
if(targetkind==TOMEM) {
for(int i=0;i<blocks.size();i++) {
DEBUG("Dumping contents of " << i);
fwrite(blocks[i],lengths[i], 1, targetfh);
}
}