multicompress.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: multicompress.cc,v 1.2 2001/02/20 07:03:18 jgg Exp $
  4. /* ######################################################################
  5. MultiCompressor
  6. This class is very complicated in order to optimize for the common
  7. case of its use, writing a large set of compressed files that are
  8. different from the old set. It spawns off compressors in parallel
  9. to maximize compression throughput and has a separate task managing
  10. the data going into the compressors.
  11. ##################################################################### */
  12. /*}}}*/
  13. // Include Files /*{{{*/
  14. #ifdef __GNUG__
  15. #pragma implementation "multicompress.h"
  16. #endif
  17. #include "multicompress.h"
  18. #include <apt-pkg/strutl.h>
  19. #include <apt-pkg/error.h>
  20. #include <apt-pkg/md5.h>
  21. #include <sys/types.h>
  22. #include <sys/stat.h>
  23. #include <utime.h>
  24. #include <unistd.h>
  25. /*}}}*/
  26. const MultiCompress::CompType MultiCompress::Compressors[] =
  27. {{".","",0,0,0,1},
  28. {"gzip",".gz","gzip","-9n","-d",2},
  29. {"bzip2",".bz2","bzip2","-9","-d",3},
  30. {}};
  31. // MultiCompress::MultiCompress - Constructor /*{{{*/
  32. // ---------------------------------------------------------------------
  33. /* Setup the file outputs, compression modes and fork the writer child */
  34. MultiCompress::MultiCompress(string Output,string Compress,
  35. mode_t Permissions,bool Write)
  36. {
  37. Outputs = 0;
  38. Outputter = -1;
  39. Input = 0;
  40. UpdateMTime = 0;
  41. this->Permissions = Permissions;
  42. /* Parse the compression string, a space separated lists of compresison
  43. types */
  44. string::const_iterator I = Compress.begin();
  45. for (; I != Compress.end();)
  46. {
  47. for (; I != Compress.end() && isspace(*I); I++);
  48. // Grab a word
  49. string::const_iterator Start = I;
  50. for (; I != Compress.end() && !isspace(*I); I++);
  51. // Find the matching compressor
  52. const CompType *Comp = Compressors;
  53. for (; Comp->Name != 0; Comp++)
  54. if (stringcmp(Start,I,Comp->Name) == 0)
  55. break;
  56. // Hmm.. unknown.
  57. if (Comp->Name == 0)
  58. {
  59. _error->Warning("Unknown Compresison Algorithm '%s'",string(Start,I).c_str());
  60. continue;
  61. }
  62. // Create and link in a new output
  63. Files *NewOut = new Files;
  64. NewOut->Next = Outputs;
  65. Outputs = NewOut;
  66. NewOut->CompressProg = Comp;
  67. NewOut->Output = Output+Comp->Extension;
  68. struct stat St;
  69. if (stat(NewOut->Output.c_str(),&St) == 0)
  70. NewOut->OldMTime = St.st_mtime;
  71. else
  72. NewOut->OldMTime = 0;
  73. }
  74. if (Write == false)
  75. return;
  76. /* Open all the temp files now so we can report any errors. File is
  77. made unreable to prevent people from touching it during creating. */
  78. for (Files *I = Outputs; I != 0; I = I->Next)
  79. I->TmpFile.Open(I->Output + ".new",FileFd::WriteEmpty,0600);
  80. if (_error->PendingError() == true)
  81. return;
  82. if (Outputs == 0)
  83. {
  84. _error->Error("Compressed output %s needs a compression set",Output.c_str());
  85. return;
  86. }
  87. Start();
  88. }
  89. /*}}}*/
  90. // MultiCompress::~MultiCompress - Destructor /*{{{*/
  91. // ---------------------------------------------------------------------
  92. /* Just erase the file linked list. */
  93. MultiCompress::~MultiCompress()
  94. {
  95. Die();
  96. for (; Outputs != 0;)
  97. {
  98. Files *Tmp = Outputs->Next;
  99. delete Outputs;
  100. Outputs = Tmp;
  101. }
  102. }
  103. /*}}}*/
  104. // MultiCompress::GetStat - Get stat information for compressed files /*{{{*/
  105. // ---------------------------------------------------------------------
  106. /* This checks each compressed file to make sure it exists and returns
  107. stat information for a random file from the collection. False means
  108. one or more of the files is missing. */
  109. bool MultiCompress::GetStat(string Output,string Compress,struct stat &St)
  110. {
  111. /* Parse the compression string, a space separated lists of compresison
  112. types */
  113. string::const_iterator I = Compress.begin();
  114. bool DidStat = false;
  115. for (; I != Compress.end();)
  116. {
  117. for (; I != Compress.end() && isspace(*I); I++);
  118. // Grab a word
  119. string::const_iterator Start = I;
  120. for (; I != Compress.end() && !isspace(*I); I++);
  121. // Find the matching compressor
  122. const CompType *Comp = Compressors;
  123. for (; Comp->Name != 0; Comp++)
  124. if (stringcmp(Start,I,Comp->Name) == 0)
  125. break;
  126. // Hmm.. unknown.
  127. if (Comp->Name == 0)
  128. continue;
  129. string Name = Output+Comp->Extension;
  130. if (stat(Name.c_str(),&St) != 0)
  131. return false;
  132. DidStat = true;
  133. }
  134. return DidStat;
  135. }
  136. /*}}}*/
  137. // MultiCompress::Start - Start up the writer child /*{{{*/
  138. // ---------------------------------------------------------------------
  139. /* Fork a child and setup the communication pipe. */
  140. bool MultiCompress::Start()
  141. {
  142. // Create a data pipe
  143. int Pipe[2] = {-1,-1};
  144. if (pipe(Pipe) != 0)
  145. return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
  146. for (int I = 0; I != 2; I++)
  147. SetCloseExec(Pipe[I],true);
  148. // The child..
  149. Outputter = fork();
  150. if (Outputter == 0)
  151. {
  152. close(Pipe[1]);
  153. Child(Pipe[0]);
  154. if (_error->PendingError() == true)
  155. {
  156. _error->DumpErrors();
  157. _exit(100);
  158. }
  159. _exit(0);
  160. };
  161. /* Tidy up the temp files, we open them in the constructor so as to
  162. get proper error reporting. Close them now. */
  163. for (Files *I = Outputs; I != 0; I = I->Next)
  164. I->TmpFile.Close();
  165. close(Pipe[0]);
  166. Input = fdopen(Pipe[1],"w");
  167. if (Input == 0)
  168. return _error->Errno("fdopen","Failed to create FILE*");
  169. if (Outputter == -1)
  170. return _error->Errno("fork","Failed to fork");
  171. return true;
  172. }
  173. /*}}}*/
  174. // MultiCompress::Die - Clean up the writer /*{{{*/
  175. // ---------------------------------------------------------------------
  176. /* */
  177. bool MultiCompress::Die()
  178. {
  179. if (Input == 0)
  180. return true;
  181. fclose(Input);
  182. Input = 0;
  183. bool Res = ExecWait(Outputter,"Compress Child",false);
  184. Outputter = -1;
  185. return Res;
  186. }
  187. /*}}}*/
  188. // MultiCompress::Finalize - Finish up writing /*{{{*/
  189. // ---------------------------------------------------------------------
  190. /* This is only necessary for statistics reporting. */
  191. bool MultiCompress::Finalize(unsigned long &OutSize)
  192. {
  193. OutSize = 0;
  194. if (Input == 0 || Die() == false)
  195. return false;
  196. time_t Now;
  197. time(&Now);
  198. // Check the mtimes to see if the files were replaced.
  199. bool Changed = false;
  200. for (Files *I = Outputs; I != 0; I = I->Next)
  201. {
  202. struct stat St;
  203. if (stat(I->Output.c_str(),&St) != 0)
  204. return _error->Error("Internal Error, Failed to create %s",
  205. I->Output.c_str());
  206. if (I->OldMTime != St.st_mtime)
  207. Changed = true;
  208. else
  209. {
  210. // Update the mtime if necessary
  211. if (UpdateMTime > 0 &&
  212. (Now - St.st_mtime > (signed)UpdateMTime || St.st_mtime > Now))
  213. {
  214. struct utimbuf Buf;
  215. Buf.actime = Buf.modtime = Now;
  216. utime(I->Output.c_str(),&Buf);
  217. Changed = true;
  218. }
  219. }
  220. // Force the file permissions
  221. if (St.st_mode != Permissions)
  222. chmod(I->Output.c_str(),Permissions);
  223. OutSize += St.st_size;
  224. }
  225. if (Changed == false)
  226. OutSize = 0;
  227. return true;
  228. }
  229. /*}}}*/
  230. // MultiCompress::OpenCompress - Open the compressor /*{{{*/
  231. // ---------------------------------------------------------------------
  232. /* This opens the compressor, either in compress mode or decompress
  233. mode. FileFd is always the compressor input/output file,
  234. OutFd is the created pipe, Input for Compress, Output for Decompress. */
  235. bool MultiCompress::OpenCompress(const CompType *Prog,int &Pid,int FileFd,
  236. int &OutFd,bool Comp)
  237. {
  238. Pid = -1;
  239. // No compression
  240. if (Prog->Binary == 0)
  241. {
  242. OutFd = dup(FileFd);
  243. return true;
  244. }
  245. // Create a data pipe
  246. int Pipe[2] = {-1,-1};
  247. if (pipe(Pipe) != 0)
  248. return _error->Errno("pipe","Failed to create subprocess IPC");
  249. for (int J = 0; J != 2; J++)
  250. SetCloseExec(Pipe[J],true);
  251. if (Comp == true)
  252. OutFd = Pipe[1];
  253. else
  254. OutFd = Pipe[0];
  255. // The child..
  256. Pid = ExecFork();
  257. if (Pid == 0)
  258. {
  259. if (Comp == true)
  260. {
  261. dup2(FileFd,STDOUT_FILENO);
  262. dup2(Pipe[0],STDIN_FILENO);
  263. }
  264. else
  265. {
  266. dup2(FileFd,STDIN_FILENO);
  267. dup2(Pipe[1],STDOUT_FILENO);
  268. }
  269. SetCloseExec(STDOUT_FILENO,false);
  270. SetCloseExec(STDIN_FILENO,false);
  271. const char *Args[3];
  272. Args[0] = Prog->Binary;
  273. if (Comp == true)
  274. Args[1] = Prog->CompArgs;
  275. else
  276. Args[1] = Prog->UnCompArgs;
  277. Args[2] = 0;
  278. execvp(Args[0],(char **)Args);
  279. cerr << "Failed to exec compressor " << Args[0] << endl;
  280. _exit(100);
  281. };
  282. if (Comp == true)
  283. close(Pipe[0]);
  284. else
  285. close(Pipe[1]);
  286. return true;
  287. }
  288. /*}}}*/
  289. // MultiCompress::OpenOld - Open an old file /*{{{*/
  290. // ---------------------------------------------------------------------
  291. /* This opens one of the original output files, possibly decompressing it. */
  292. bool MultiCompress::OpenOld(int &Fd,int &Proc)
  293. {
  294. Files *Best = Outputs;
  295. for (Files *I = Outputs; I != 0; I = I->Next)
  296. if (Best->CompressProg->Cost > I->CompressProg->Cost)
  297. Best = I;
  298. // Open the file
  299. FileFd F(Best->Output,FileFd::ReadOnly);
  300. if (_error->PendingError() == true)
  301. return false;
  302. // Decompress the file so we can read it
  303. if (OpenCompress(Best->CompressProg,Proc,F.Fd(),Fd,false) == false)
  304. return false;
  305. return true;
  306. }
  307. /*}}}*/
  308. // MultiCompress::CloseOld - Close the old file /*{{{*/
  309. // ---------------------------------------------------------------------
  310. /* */
  311. bool MultiCompress::CloseOld(int Fd,int Proc)
  312. {
  313. close(Fd);
  314. if (Proc != -1)
  315. if (ExecWait(Proc,"decompressor",false) == false)
  316. return false;
  317. return true;
  318. }
  319. /*}}}*/
  320. // MultiCompress::Child - The writer child /*{{{*/
  321. // ---------------------------------------------------------------------
  322. /* The child process forks a bunch of compression children and takes
  323. input on FD and passes it to all the compressor childer. On the way it
  324. computes the MD5 of the raw data. After this the raw data in the
  325. original files is compared to see if this data is new. If the data
  326. is new then the temp files are renamed, otherwise they are erased. */
  327. bool MultiCompress::Child(int FD)
  328. {
  329. // Start the compression children.
  330. for (Files *I = Outputs; I != 0; I = I->Next)
  331. {
  332. if (OpenCompress(I->CompressProg,I->CompressProc,I->TmpFile.Fd(),
  333. I->Fd,true) == false)
  334. return false;
  335. }
  336. /* Okay, now we just feed data from FD to all the other FDs. Also
  337. stash a hash of the data to use later. */
  338. SetNonBlock(FD,false);
  339. unsigned char Buffer[32*1024];
  340. unsigned long FileSize = 0;
  341. MD5Summation MD5;
  342. while (1)
  343. {
  344. WaitFd(FD,false);
  345. int Res = read(FD,Buffer,sizeof(Buffer));
  346. if (Res == 0)
  347. break;
  348. if (Res < 0)
  349. continue;
  350. MD5.Add(Buffer,Res);
  351. FileSize += Res;
  352. for (Files *I = Outputs; I != 0; I = I->Next)
  353. {
  354. if (write(I->Fd,Buffer,Res) != Res)
  355. {
  356. _error->Errno("write","IO to subprocess/file failed");
  357. break;
  358. }
  359. }
  360. }
  361. // Close all the writers
  362. for (Files *I = Outputs; I != 0; I = I->Next)
  363. close(I->Fd);
  364. // Wait for the compressors to exit
  365. for (Files *I = Outputs; I != 0; I = I->Next)
  366. {
  367. if (I->CompressProc != -1)
  368. ExecWait(I->CompressProc,I->CompressProg->Binary,false);
  369. }
  370. if (_error->PendingError() == true)
  371. return false;
  372. /* Now we have to copy the files over, or erase them if they
  373. have not changed. First find the cheapest decompressor */
  374. bool Missing = false;
  375. for (Files *I = Outputs; I != 0; I = I->Next)
  376. {
  377. if (I->OldMTime == 0)
  378. {
  379. Missing = true;
  380. break;
  381. }
  382. }
  383. // Check the MD5 of the lowest cost entity.
  384. while (Missing == false)
  385. {
  386. int CompFd = -1;
  387. int Proc = -1;
  388. if (OpenOld(CompFd,Proc) == false)
  389. {
  390. _error->Discard();
  391. break;
  392. }
  393. // Compute the hash
  394. MD5Summation OldMD5;
  395. unsigned long NewFileSize = 0;
  396. while (1)
  397. {
  398. int Res = read(CompFd,Buffer,sizeof(Buffer));
  399. if (Res == 0)
  400. break;
  401. if (Res < 0)
  402. return _error->Errno("read","Failed to read while computing MD5");
  403. NewFileSize += Res;
  404. OldMD5.Add(Buffer,Res);
  405. }
  406. // Tidy the compressor
  407. if (CloseOld(CompFd,Proc) == false)
  408. return false;
  409. // Check the hash
  410. if (OldMD5.Result() == MD5.Result() &&
  411. FileSize == NewFileSize)
  412. {
  413. for (Files *I = Outputs; I != 0; I = I->Next)
  414. {
  415. I->TmpFile.Close();
  416. if (unlink(I->TmpFile.Name().c_str()) != 0)
  417. _error->Errno("unlink","Problem unlinking %s",
  418. I->TmpFile.Name().c_str());
  419. }
  420. return !_error->PendingError();
  421. }
  422. break;
  423. }
  424. // Finalize
  425. for (Files *I = Outputs; I != 0; I = I->Next)
  426. {
  427. // Set the correct file modes
  428. fchmod(I->TmpFile.Fd(),Permissions);
  429. if (rename(I->TmpFile.Name().c_str(),I->Output.c_str()) != 0)
  430. _error->Errno("rename","Failed to rename %s to %s",
  431. I->TmpFile.Name().c_str(),I->Output.c_str());
  432. I->TmpFile.Close();
  433. }
  434. return !_error->PendingError();
  435. }
  436. /*}}}*/