multicompress.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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/fileutl.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. #include "multicompress.h"
  25. #include <apti18n.h>
  26. /*}}}*/
  27. using namespace std;
  28. // MultiCompress::MultiCompress - Constructor /*{{{*/
  29. // ---------------------------------------------------------------------
  30. /* Setup the file outputs, compression modes and fork the writer child */
  31. MultiCompress::MultiCompress(string const &Output,string const &Compress,
  32. mode_t const &Permissions,bool const &Write) :
  33. Permissions(Permissions)
  34. {
  35. Outputs = 0;
  36. Outputter = -1;
  37. Input = 0;
  38. UpdateMTime = 0;
  39. /* Parse the compression string, a space separated lists of compresison
  40. types */
  41. string::const_iterator I = Compress.begin();
  42. for (; I != Compress.end();)
  43. {
  44. for (; I != Compress.end() && isspace(*I); ++I);
  45. // Grab a word
  46. string::const_iterator Start = I;
  47. for (; I != Compress.end() && !isspace(*I); ++I);
  48. // Find the matching compressor
  49. std::vector<APT::Configuration::Compressor> Compressors = APT::Configuration::getCompressors();
  50. std::vector<APT::Configuration::Compressor>::const_iterator Comp = Compressors.begin();
  51. for (; Comp != Compressors.end(); ++Comp)
  52. if (stringcmp(Start,I,Comp->Name.c_str()) == 0)
  53. break;
  54. // Hmm.. unknown.
  55. if (Comp == Compressors.end())
  56. {
  57. _error->Warning(_("Unknown compression algorithm '%s'"),string(Start,I).c_str());
  58. continue;
  59. }
  60. // Create and link in a new output
  61. Files *NewOut = new Files;
  62. NewOut->Next = Outputs;
  63. Outputs = NewOut;
  64. NewOut->CompressProg = *Comp;
  65. NewOut->Output = Output+Comp->Extension;
  66. struct stat St;
  67. if (stat(NewOut->Output.c_str(),&St) == 0)
  68. NewOut->OldMTime = St.st_mtime;
  69. else
  70. NewOut->OldMTime = 0;
  71. }
  72. if (Write == false)
  73. return;
  74. /* Open all the temp files now so we can report any errors. File is
  75. made unreable to prevent people from touching it during creating. */
  76. for (Files *I = Outputs; I != 0; I = I->Next)
  77. I->TmpFile.Open(I->Output + ".new", FileFd::WriteOnly | FileFd::Create | FileFd::Empty, FileFd::Extension, 0600);
  78. if (_error->PendingError() == true)
  79. return;
  80. if (Outputs == 0)
  81. {
  82. _error->Error(_("Compressed output %s needs a compression set"),Output.c_str());
  83. return;
  84. }
  85. Start();
  86. }
  87. /*}}}*/
  88. // MultiCompress::~MultiCompress - Destructor /*{{{*/
  89. // ---------------------------------------------------------------------
  90. /* Just erase the file linked list. */
  91. MultiCompress::~MultiCompress()
  92. {
  93. Die();
  94. for (; Outputs != 0;)
  95. {
  96. Files *Tmp = Outputs->Next;
  97. delete Outputs;
  98. Outputs = Tmp;
  99. }
  100. }
  101. /*}}}*/
  102. // MultiCompress::GetStat - Get stat information for compressed files /*{{{*/
  103. // ---------------------------------------------------------------------
  104. /* This checks each compressed file to make sure it exists and returns
  105. stat information for a random file from the collection. False means
  106. one or more of the files is missing. */
  107. bool MultiCompress::GetStat(string const &Output,string const &Compress,struct stat &St)
  108. {
  109. /* Parse the compression string, a space separated lists of compresison
  110. types */
  111. string::const_iterator I = Compress.begin();
  112. bool DidStat = false;
  113. for (; I != Compress.end();)
  114. {
  115. for (; I != Compress.end() && isspace(*I); ++I);
  116. // Grab a word
  117. string::const_iterator Start = I;
  118. for (; I != Compress.end() && !isspace(*I); ++I);
  119. // Find the matching compressor
  120. std::vector<APT::Configuration::Compressor> Compressors = APT::Configuration::getCompressors();
  121. std::vector<APT::Configuration::Compressor>::const_iterator Comp = Compressors.begin();
  122. for (; Comp != Compressors.end(); ++Comp)
  123. if (stringcmp(Start,I,Comp->Name.c_str()) == 0)
  124. break;
  125. // Hmm.. unknown.
  126. if (Comp == Compressors.end())
  127. continue;
  128. string Name = Output+Comp->Extension;
  129. if (stat(Name.c_str(),&St) != 0)
  130. return false;
  131. DidStat = true;
  132. }
  133. return DidStat;
  134. }
  135. /*}}}*/
  136. // MultiCompress::Start - Start up the writer child /*{{{*/
  137. // ---------------------------------------------------------------------
  138. /* Fork a child and setup the communication pipe. */
  139. bool MultiCompress::Start()
  140. {
  141. // Create a data pipe
  142. int Pipe[2] = {-1,-1};
  143. if (pipe(Pipe) != 0)
  144. return _error->Errno("pipe",_("Failed to create IPC pipe to subprocess"));
  145. for (int I = 0; I != 2; I++)
  146. SetCloseExec(Pipe[I],true);
  147. // The child..
  148. Outputter = fork();
  149. if (Outputter == 0)
  150. {
  151. close(Pipe[1]);
  152. Child(Pipe[0]);
  153. if (_error->PendingError() == true)
  154. {
  155. _error->DumpErrors();
  156. _exit(100);
  157. }
  158. _exit(0);
  159. };
  160. close(Pipe[0]);
  161. Input = fdopen(Pipe[1],"w");
  162. if (Input == 0)
  163. return _error->Errno("fdopen",_("Failed to create FILE*"));
  164. if (Outputter == -1)
  165. return _error->Errno("fork",_("Failed to fork"));
  166. return true;
  167. }
  168. /*}}}*/
  169. // MultiCompress::Die - Clean up the writer /*{{{*/
  170. // ---------------------------------------------------------------------
  171. /* */
  172. bool MultiCompress::Die()
  173. {
  174. if (Input == 0)
  175. return true;
  176. fclose(Input);
  177. Input = 0;
  178. bool Res = ExecWait(Outputter,_("Compress child"),false);
  179. Outputter = -1;
  180. return Res;
  181. }
  182. /*}}}*/
  183. // MultiCompress::Finalize - Finish up writing /*{{{*/
  184. // ---------------------------------------------------------------------
  185. /* This is only necessary for statistics reporting. */
  186. bool MultiCompress::Finalize(unsigned long long &OutSize)
  187. {
  188. OutSize = 0;
  189. if (Input == 0 || Die() == false)
  190. return false;
  191. time_t Now;
  192. time(&Now);
  193. // Check the mtimes to see if the files were replaced.
  194. bool Changed = false;
  195. for (Files *I = Outputs; I != 0; I = I->Next)
  196. {
  197. struct stat St;
  198. if (stat(I->Output.c_str(),&St) != 0)
  199. return _error->Error(_("Internal error, failed to create %s"),
  200. I->Output.c_str());
  201. if (I->OldMTime != St.st_mtime)
  202. Changed = true;
  203. else
  204. {
  205. // Update the mtime if necessary
  206. if (UpdateMTime > 0 &&
  207. (Now - St.st_mtime > (signed)UpdateMTime || St.st_mtime > Now))
  208. {
  209. struct utimbuf Buf;
  210. Buf.actime = Buf.modtime = Now;
  211. utime(I->Output.c_str(),&Buf);
  212. Changed = true;
  213. }
  214. }
  215. // Force the file permissions
  216. if (St.st_mode != Permissions)
  217. chmod(I->Output.c_str(),Permissions);
  218. OutSize += St.st_size;
  219. }
  220. if (Changed == false)
  221. OutSize = 0;
  222. return true;
  223. }
  224. /*}}}*/
  225. // MultiCompress::OpenOld - Open an old file /*{{{*/
  226. // ---------------------------------------------------------------------
  227. /* This opens one of the original output files, possibly decompressing it. */
  228. bool MultiCompress::OpenOld(FileFd &Fd)
  229. {
  230. Files *Best = Outputs;
  231. for (Files *I = Outputs; I != 0; I = I->Next)
  232. if (Best->CompressProg.Cost > I->CompressProg.Cost)
  233. Best = I;
  234. // Open the file
  235. return Fd.Open(Best->Output, FileFd::ReadOnly, FileFd::Extension);
  236. }
  237. /*}}}*/
  238. // MultiCompress::Child - The writer child /*{{{*/
  239. // ---------------------------------------------------------------------
  240. /* The child process forks a bunch of compression children and takes
  241. input on FD and passes it to all the compressor child. On the way it
  242. computes the MD5 of the raw data. After this the raw data in the
  243. original files is compared to see if this data is new. If the data
  244. is new then the temp files are renamed, otherwise they are erased. */
  245. bool MultiCompress::Child(int const &FD)
  246. {
  247. /* Okay, now we just feed data from FD to all the other FDs. Also
  248. stash a hash of the data to use later. */
  249. SetNonBlock(FD,false);
  250. unsigned char Buffer[32*1024];
  251. unsigned long long FileSize = 0;
  252. MD5Summation MD5;
  253. while (1)
  254. {
  255. WaitFd(FD,false);
  256. int Res = read(FD,Buffer,sizeof(Buffer));
  257. if (Res == 0)
  258. break;
  259. if (Res < 0)
  260. continue;
  261. MD5.Add(Buffer,Res);
  262. FileSize += Res;
  263. for (Files *I = Outputs; I != 0; I = I->Next)
  264. {
  265. if (I->TmpFile.Write(Buffer, Res) == false)
  266. {
  267. _error->Errno("write",_("IO to subprocess/file failed"));
  268. break;
  269. }
  270. }
  271. }
  272. if (_error->PendingError() == true)
  273. return false;
  274. /* Now we have to copy the files over, or erase them if they
  275. have not changed. First find the cheapest decompressor */
  276. bool Missing = false;
  277. for (Files *I = Outputs; I != 0; I = I->Next)
  278. {
  279. if (I->OldMTime == 0)
  280. {
  281. Missing = true;
  282. break;
  283. }
  284. }
  285. // Check the MD5 of the lowest cost entity.
  286. while (Missing == false)
  287. {
  288. FileFd CompFd;
  289. if (OpenOld(CompFd) == false)
  290. {
  291. _error->Discard();
  292. break;
  293. }
  294. // Compute the hash
  295. MD5Summation OldMD5;
  296. unsigned long long NewFileSize = 0;
  297. while (1)
  298. {
  299. unsigned long long Res = 0;
  300. if (CompFd.Read(Buffer,sizeof(Buffer), &Res) == false)
  301. return _error->Errno("read",_("Failed to read while computing MD5"));
  302. if (Res == 0)
  303. break;
  304. NewFileSize += Res;
  305. OldMD5.Add(Buffer,Res);
  306. }
  307. CompFd.Close();
  308. // Check the hash
  309. if (OldMD5.Result() == MD5.Result() &&
  310. FileSize == NewFileSize)
  311. {
  312. for (Files *I = Outputs; I != 0; I = I->Next)
  313. {
  314. I->TmpFile.Close();
  315. if (unlink(I->TmpFile.Name().c_str()) != 0)
  316. _error->Errno("unlink",_("Problem unlinking %s"),
  317. I->TmpFile.Name().c_str());
  318. }
  319. return !_error->PendingError();
  320. }
  321. break;
  322. }
  323. // Finalize
  324. for (Files *I = Outputs; I != 0; I = I->Next)
  325. {
  326. // Set the correct file modes
  327. fchmod(I->TmpFile.Fd(),Permissions);
  328. if (rename(I->TmpFile.Name().c_str(),I->Output.c_str()) != 0)
  329. _error->Errno("rename",_("Failed to rename %s to %s"),
  330. I->TmpFile.Name().c_str(),I->Output.c_str());
  331. I->TmpFile.Close();
  332. }
  333. return !_error->PendingError();
  334. }
  335. /*}}}*/