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.
 
 
 
 
 
 

498 lines
13 KiB

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