multicompress.cc 13 KB

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