multicompress.cc 13 KB

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