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