You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

multicompress.cc 10 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. /* ######################################################################
  4. MultiCompressor
  5. This class is very complicated in order to optimize for the common
  6. case of its use, writing a large set of compressed files that are
  7. different from the old set. It spawns off compressors in parallel
  8. to maximize compression throughput and has a separate task managing
  9. the data going into the compressors.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #include <config.h>
  14. #include <apt-pkg/aptconfiguration.h>
  15. #include <apt-pkg/error.h>
  16. #include <apt-pkg/fileutl.h>
  17. #include <apt-pkg/hashsum_template.h>
  18. #include <apt-pkg/md5.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <ctype.h>
  21. #include <sys/stat.h>
  22. #include <sys/time.h>
  23. #include <sys/types.h>
  24. #include <unistd.h>
  25. #include <algorithm>
  26. #include <vector>
  27. #include "multicompress.h"
  28. #include <apti18n.h>
  29. /*}}}*/
  30. using namespace std;
  31. static std::vector<APT::Configuration::Compressor>::const_iterator findMatchingCompressor(std::string::const_iterator &I,
  32. std::string::const_iterator const &End, std::vector<APT::Configuration::Compressor> const &Compressors)
  33. {
  34. // Grab a word (aka: a compressor name)
  35. for (; I != End && isspace(*I); ++I);
  36. string::const_iterator Start = I;
  37. for (; I != End && !isspace(*I); ++I);
  38. auto const Comp = std::find_if(Compressors.begin(), Compressors.end(),
  39. [&](APT::Configuration::Compressor const &C) { return stringcmp(Start, I, C.Name.c_str()) == 0;
  40. });
  41. if (Comp == Compressors.end())
  42. _error->Warning(_("Unknown compression algorithm '%s'"),string(Start,I).c_str());
  43. return Comp;
  44. }
  45. // MultiCompress::MultiCompress - Constructor /*{{{*/
  46. // ---------------------------------------------------------------------
  47. /* Setup the file outputs, compression modes and fork the writer child */
  48. MultiCompress::MultiCompress(string const &Output,string const &Compress,
  49. mode_t const &Permissions,bool const &Write) :
  50. Permissions(Permissions)
  51. {
  52. Outputs = 0;
  53. Outputter = -1;
  54. UpdateMTime = 0;
  55. auto const Compressors = APT::Configuration::getCompressors();
  56. // Parse the compression string, a space separated lists of compression types
  57. for (auto I = Compress.cbegin(); I != Compress.cend();)
  58. {
  59. auto const Comp = findMatchingCompressor(I, Compress.cend(), Compressors);
  60. if (Comp == Compressors.end())
  61. continue;
  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. auto const Compressors = APT::Configuration::getCompressors();
  112. // Parse the compression string, a space separated lists of compression types
  113. bool DidStat = false;
  114. for (auto I = Compress.cbegin(); I != Compress.cend();)
  115. {
  116. auto const Comp = findMatchingCompressor(I, Compress.cend(), Compressors);
  117. if (Comp == Compressors.end())
  118. continue;
  119. string Name = Output + Comp->Extension;
  120. if (stat(Name.c_str(),&St) != 0)
  121. return false;
  122. DidStat = true;
  123. }
  124. return DidStat;
  125. }
  126. /*}}}*/
  127. // MultiCompress::Start - Start up the writer child /*{{{*/
  128. // ---------------------------------------------------------------------
  129. /* Fork a child and setup the communication pipe. */
  130. bool MultiCompress::Start()
  131. {
  132. // Create a data pipe
  133. int Pipe[2] = {-1,-1};
  134. if (pipe(Pipe) != 0)
  135. return _error->Errno("pipe",_("Failed to create IPC pipe to subprocess"));
  136. for (int I = 0; I != 2; I++)
  137. SetCloseExec(Pipe[I],true);
  138. // The child..
  139. Outputter = fork();
  140. if (Outputter == 0)
  141. {
  142. close(Pipe[1]);
  143. Child(Pipe[0]);
  144. if (_error->PendingError() == true)
  145. {
  146. _error->DumpErrors();
  147. _exit(100);
  148. }
  149. _exit(0);
  150. };
  151. close(Pipe[0]);
  152. if (Input.OpenDescriptor(Pipe[1], FileFd::WriteOnly, true) == false)
  153. return false;
  154. if (Outputter == -1)
  155. return _error->Errno("fork",_("Failed to fork"));
  156. return true;
  157. }
  158. /*}}}*/
  159. // MultiCompress::Die - Clean up the writer /*{{{*/
  160. // ---------------------------------------------------------------------
  161. /* */
  162. bool MultiCompress::Die()
  163. {
  164. if (Input.IsOpen() == false)
  165. return true;
  166. Input.Close();
  167. bool Res = ExecWait(Outputter,_("Compress child"),false);
  168. Outputter = -1;
  169. return Res;
  170. }
  171. /*}}}*/
  172. // MultiCompress::Finalize - Finish up writing /*{{{*/
  173. // ---------------------------------------------------------------------
  174. /* This is only necessary for statistics reporting. */
  175. bool MultiCompress::Finalize(unsigned long long &OutSize)
  176. {
  177. OutSize = 0;
  178. if (Input.IsOpen() == false || Die() == false)
  179. return false;
  180. time_t Now;
  181. time(&Now);
  182. // Check the mtimes to see if the files were replaced.
  183. bool Changed = false;
  184. for (Files *I = Outputs; I != 0; I = I->Next)
  185. {
  186. struct stat St;
  187. if (stat(I->Output.c_str(),&St) != 0)
  188. return _error->Error(_("Internal error, failed to create %s"),
  189. I->Output.c_str());
  190. if (I->OldMTime != St.st_mtime)
  191. Changed = true;
  192. else
  193. {
  194. // Update the mtime if necessary
  195. if (UpdateMTime > 0 &&
  196. (Now - St.st_mtime > (signed)UpdateMTime || St.st_mtime > Now))
  197. {
  198. utimes(I->Output.c_str(), NULL);
  199. Changed = true;
  200. }
  201. }
  202. // Force the file permissions
  203. if (St.st_mode != Permissions)
  204. chmod(I->Output.c_str(),Permissions);
  205. OutSize += St.st_size;
  206. }
  207. if (Changed == false)
  208. OutSize = 0;
  209. return true;
  210. }
  211. /*}}}*/
  212. // MultiCompress::OpenOld - Open an old file /*{{{*/
  213. // ---------------------------------------------------------------------
  214. /* This opens one of the original output files, possibly decompressing it. */
  215. bool MultiCompress::OpenOld(FileFd &Fd)
  216. {
  217. Files *Best = Outputs;
  218. for (Files *I = Outputs; I != 0; I = I->Next)
  219. if (Best->CompressProg.Cost > I->CompressProg.Cost)
  220. Best = I;
  221. // Open the file
  222. return Fd.Open(Best->Output, FileFd::ReadOnly, FileFd::Extension);
  223. }
  224. /*}}}*/
  225. // MultiCompress::Child - The writer child /*{{{*/
  226. // ---------------------------------------------------------------------
  227. /* The child process forks a bunch of compression children and takes
  228. input on FD and passes it to all the compressor child. On the way it
  229. computes the MD5 of the raw data. After this the raw data in the
  230. original files is compared to see if this data is new. If the data
  231. is new then the temp files are renamed, otherwise they are erased. */
  232. bool MultiCompress::Child(int const &FD)
  233. {
  234. /* Okay, now we just feed data from FD to all the other FDs. Also
  235. stash a hash of the data to use later. */
  236. SetNonBlock(FD,false);
  237. unsigned char Buffer[32*1024];
  238. unsigned long long FileSize = 0;
  239. MD5Summation MD5;
  240. while (1)
  241. {
  242. WaitFd(FD,false);
  243. int Res = read(FD,Buffer,sizeof(Buffer));
  244. if (Res == 0)
  245. break;
  246. if (Res < 0)
  247. continue;
  248. MD5.Add(Buffer,Res);
  249. FileSize += Res;
  250. for (Files *I = Outputs; I != 0; I = I->Next)
  251. {
  252. if (I->TmpFile.Write(Buffer, Res) == false)
  253. {
  254. _error->Errno("write",_("IO to subprocess/file failed"));
  255. break;
  256. }
  257. }
  258. }
  259. if (_error->PendingError() == true)
  260. return false;
  261. /* Now we have to copy the files over, or erase them if they
  262. have not changed. First find the cheapest decompressor */
  263. bool Missing = false;
  264. for (Files *I = Outputs; I != 0; I = I->Next)
  265. {
  266. if (I->OldMTime == 0)
  267. {
  268. Missing = true;
  269. break;
  270. }
  271. }
  272. // Check the MD5 of the lowest cost entity.
  273. while (Missing == false)
  274. {
  275. FileFd CompFd;
  276. if (OpenOld(CompFd) == false)
  277. {
  278. _error->Discard();
  279. break;
  280. }
  281. // Compute the hash
  282. MD5Summation OldMD5;
  283. unsigned long long NewFileSize = 0;
  284. while (1)
  285. {
  286. unsigned long long Res = 0;
  287. if (CompFd.Read(Buffer,sizeof(Buffer), &Res) == false)
  288. return _error->Errno("read",_("Failed to read while computing MD5"));
  289. if (Res == 0)
  290. break;
  291. NewFileSize += Res;
  292. OldMD5.Add(Buffer,Res);
  293. }
  294. CompFd.Close();
  295. // Check the hash
  296. if (OldMD5.Result() == MD5.Result() &&
  297. FileSize == NewFileSize)
  298. {
  299. for (Files *I = Outputs; I != 0; I = I->Next)
  300. {
  301. I->TmpFile.Close();
  302. RemoveFile("MultiCompress::Child", I->TmpFile.Name());
  303. }
  304. return !_error->PendingError();
  305. }
  306. break;
  307. }
  308. // Finalize
  309. for (Files *I = Outputs; I != 0; I = I->Next)
  310. {
  311. // Set the correct file modes
  312. chmod(I->TmpFile.Name().c_str(),Permissions);
  313. if (rename(I->TmpFile.Name().c_str(),I->Output.c_str()) != 0)
  314. _error->Errno("rename",_("Failed to rename %s to %s"),
  315. I->TmpFile.Name().c_str(),I->Output.c_str());
  316. I->TmpFile.Close();
  317. }
  318. return !_error->PendingError();
  319. }
  320. /*}}}*/