multicompress.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 <apt-pkg/aptconfiguration.h>
  20. #include <apt-pkg/hashsum_template.h>
  21. #include <ctype.h>
  22. #include <vector>
  23. #include <sys/types.h>
  24. #include <sys/stat.h>
  25. #include <sys/time.h>
  26. #include <unistd.h>
  27. #include "multicompress.h"
  28. #include <apti18n.h>
  29. /*}}}*/
  30. using namespace std;
  31. // MultiCompress::MultiCompress - Constructor /*{{{*/
  32. // ---------------------------------------------------------------------
  33. /* Setup the file outputs, compression modes and fork the writer child */
  34. MultiCompress::MultiCompress(string const &Output,string const &Compress,
  35. mode_t const &Permissions,bool const &Write) :
  36. Permissions(Permissions)
  37. {
  38. Outputs = 0;
  39. Outputter = -1;
  40. UpdateMTime = 0;
  41. /* Parse the compression string, a space separated lists of compresison
  42. types */
  43. string::const_iterator I = Compress.begin();
  44. for (; I != Compress.end();)
  45. {
  46. for (; I != Compress.end() && isspace(*I); ++I);
  47. // Grab a word
  48. string::const_iterator Start = I;
  49. for (; I != Compress.end() && !isspace(*I); ++I);
  50. // Find the matching compressor
  51. std::vector<APT::Configuration::Compressor> Compressors = APT::Configuration::getCompressors();
  52. std::vector<APT::Configuration::Compressor>::const_iterator Comp = Compressors.begin();
  53. for (; Comp != Compressors.end(); ++Comp)
  54. if (stringcmp(Start,I,Comp->Name.c_str()) == 0)
  55. break;
  56. // Hmm.. unknown.
  57. if (Comp == Compressors.end())
  58. {
  59. _error->Warning(_("Unknown compression 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::WriteOnly | FileFd::Create | FileFd::Empty, FileFd::Extension, 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 const &Output,string const &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. std::vector<APT::Configuration::Compressor> Compressors = APT::Configuration::getCompressors();
  123. std::vector<APT::Configuration::Compressor>::const_iterator Comp = Compressors.begin();
  124. for (; Comp != Compressors.end(); ++Comp)
  125. if (stringcmp(Start,I,Comp->Name.c_str()) == 0)
  126. break;
  127. // Hmm.. unknown.
  128. if (Comp == Compressors.end())
  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. close(Pipe[0]);
  163. if (Input.OpenDescriptor(Pipe[1], FileFd::WriteOnly, true) == false)
  164. return false;
  165. if (Outputter == -1)
  166. return _error->Errno("fork",_("Failed to fork"));
  167. return true;
  168. }
  169. /*}}}*/
  170. // MultiCompress::Die - Clean up the writer /*{{{*/
  171. // ---------------------------------------------------------------------
  172. /* */
  173. bool MultiCompress::Die()
  174. {
  175. if (Input.IsOpen() == false)
  176. return true;
  177. Input.Close();
  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.IsOpen() == false || 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. utimes(I->Output.c_str(), NULL);
  210. Changed = true;
  211. }
  212. }
  213. // Force the file permissions
  214. if (St.st_mode != Permissions)
  215. chmod(I->Output.c_str(),Permissions);
  216. OutSize += St.st_size;
  217. }
  218. if (Changed == false)
  219. OutSize = 0;
  220. return true;
  221. }
  222. /*}}}*/
  223. // MultiCompress::OpenOld - Open an old file /*{{{*/
  224. // ---------------------------------------------------------------------
  225. /* This opens one of the original output files, possibly decompressing it. */
  226. bool MultiCompress::OpenOld(FileFd &Fd)
  227. {
  228. Files *Best = Outputs;
  229. for (Files *I = Outputs; I != 0; I = I->Next)
  230. if (Best->CompressProg.Cost > I->CompressProg.Cost)
  231. Best = I;
  232. // Open the file
  233. return Fd.Open(Best->Output, FileFd::ReadOnly, FileFd::Extension);
  234. }
  235. /*}}}*/
  236. // MultiCompress::Child - The writer child /*{{{*/
  237. // ---------------------------------------------------------------------
  238. /* The child process forks a bunch of compression children and takes
  239. input on FD and passes it to all the compressor child. On the way it
  240. computes the MD5 of the raw data. After this the raw data in the
  241. original files is compared to see if this data is new. If the data
  242. is new then the temp files are renamed, otherwise they are erased. */
  243. bool MultiCompress::Child(int const &FD)
  244. {
  245. /* Okay, now we just feed data from FD to all the other FDs. Also
  246. stash a hash of the data to use later. */
  247. SetNonBlock(FD,false);
  248. unsigned char Buffer[32*1024];
  249. unsigned long long FileSize = 0;
  250. MD5Summation MD5;
  251. while (1)
  252. {
  253. WaitFd(FD,false);
  254. int Res = read(FD,Buffer,sizeof(Buffer));
  255. if (Res == 0)
  256. break;
  257. if (Res < 0)
  258. continue;
  259. MD5.Add(Buffer,Res);
  260. FileSize += Res;
  261. for (Files *I = Outputs; I != 0; I = I->Next)
  262. {
  263. if (I->TmpFile.Write(Buffer, Res) == false)
  264. {
  265. _error->Errno("write",_("IO to subprocess/file failed"));
  266. break;
  267. }
  268. }
  269. }
  270. if (_error->PendingError() == true)
  271. return false;
  272. /* Now we have to copy the files over, or erase them if they
  273. have not changed. First find the cheapest decompressor */
  274. bool Missing = false;
  275. for (Files *I = Outputs; I != 0; I = I->Next)
  276. {
  277. if (I->OldMTime == 0)
  278. {
  279. Missing = true;
  280. break;
  281. }
  282. }
  283. // Check the MD5 of the lowest cost entity.
  284. while (Missing == false)
  285. {
  286. FileFd CompFd;
  287. if (OpenOld(CompFd) == false)
  288. {
  289. _error->Discard();
  290. break;
  291. }
  292. // Compute the hash
  293. MD5Summation OldMD5;
  294. unsigned long long NewFileSize = 0;
  295. while (1)
  296. {
  297. unsigned long long Res = 0;
  298. if (CompFd.Read(Buffer,sizeof(Buffer), &Res) == false)
  299. return _error->Errno("read",_("Failed to read while computing MD5"));
  300. if (Res == 0)
  301. break;
  302. NewFileSize += Res;
  303. OldMD5.Add(Buffer,Res);
  304. }
  305. CompFd.Close();
  306. // Check the hash
  307. if (OldMD5.Result() == MD5.Result() &&
  308. FileSize == NewFileSize)
  309. {
  310. for (Files *I = Outputs; I != 0; I = I->Next)
  311. {
  312. I->TmpFile.Close();
  313. RemoveFile("MultiCompress::Child", I->TmpFile.Name());
  314. }
  315. return !_error->PendingError();
  316. }
  317. break;
  318. }
  319. // Finalize
  320. for (Files *I = Outputs; I != 0; I = I->Next)
  321. {
  322. // Set the correct file modes
  323. chmod(I->TmpFile.Name().c_str(),Permissions);
  324. if (rename(I->TmpFile.Name().c_str(),I->Output.c_str()) != 0)
  325. _error->Errno("rename",_("Failed to rename %s to %s"),
  326. I->TmpFile.Name().c_str(),I->Output.c_str());
  327. I->TmpFile.Close();
  328. }
  329. return !_error->PendingError();
  330. }
  331. /*}}}*/