CompressingLogFileManager.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. #import "CompressingLogFileManager.h"
  2. #import <zlib.h>
  3. // We probably shouldn't be using DDLog() statements within the DDLog implementation.
  4. // But we still want to leave our log statements for any future debugging,
  5. // and to allow other developers to trace the implementation (which is a great learning tool).
  6. //
  7. // So we use primitive logging macros around NSLog.
  8. // We maintain the NS prefix on the macros to be explicit about the fact that we're using NSLog.
  9. #define LOG_LEVEL 4
  10. #define NSLogError(frmt, ...) do{ if(LOG_LEVEL >= 1) NSLog(frmt, ##__VA_ARGS__); } while(0)
  11. #define NSLogWarn(frmt, ...) do{ if(LOG_LEVEL >= 2) NSLog(frmt, ##__VA_ARGS__); } while(0)
  12. #define NSLogInfo(frmt, ...) do{ if(LOG_LEVEL >= 3) NSLog(frmt, ##__VA_ARGS__); } while(0)
  13. #define NSLogVerbose(frmt, ...) do{ if(LOG_LEVEL >= 4) NSLog(frmt, ##__VA_ARGS__); } while(0)
  14. @interface CompressingLogFileManager (/* Must be nameless for properties */)
  15. @property (readwrite) BOOL isCompressing;
  16. @end
  17. @interface DDLogFileInfo (Compressor)
  18. @property (nonatomic, readonly) BOOL isCompressed;
  19. - (NSString *)tempFilePathByAppendingPathExtension:(NSString *)newExt;
  20. - (NSString *)fileNameByAppendingPathExtension:(NSString *)newExt;
  21. @end
  22. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  23. #pragma mark -
  24. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  25. @implementation CompressingLogFileManager
  26. @synthesize isCompressing;
  27. - (id)init
  28. {
  29. return [self initWithLogsDirectory:nil];
  30. }
  31. - (id)initWithLogsDirectory:(NSString *)aLogsDirectory
  32. {
  33. if ((self = [super initWithLogsDirectory:aLogsDirectory]))
  34. {
  35. upToDate = NO;
  36. // Check for any files that need to be compressed.
  37. // But don't start right away.
  38. // Wait for the app startup process to finish.
  39. [self performSelector:@selector(compressNextLogFile) withObject:nil afterDelay:5.0];
  40. }
  41. return self;
  42. }
  43. - (void)dealloc
  44. {
  45. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(compressNextLogFile) object:nil];
  46. }
  47. - (void)compressLogFile:(DDLogFileInfo *)logFile
  48. {
  49. self.isCompressing = YES;
  50. CompressingLogFileManager* __weak weakSelf = self;
  51. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  52. [weakSelf backgroundThread_CompressLogFile:logFile];
  53. });
  54. }
  55. - (void)compressNextLogFile
  56. {
  57. if (self.isCompressing)
  58. {
  59. // We're already compressing a file.
  60. // Wait until it's done to move onto the next file.
  61. return;
  62. }
  63. NSLogVerbose(@"CompressingLogFileManager: compressNextLogFile");
  64. upToDate = NO;
  65. NSArray *sortedLogFileInfos = [self sortedLogFileInfos];
  66. NSUInteger count = [sortedLogFileInfos count];
  67. if (count == 0)
  68. {
  69. // Nothing to compress
  70. upToDate = YES;
  71. return;
  72. }
  73. NSUInteger i = count;
  74. while (i > 0)
  75. {
  76. DDLogFileInfo *logFileInfo = [sortedLogFileInfos objectAtIndex:(i - 1)];
  77. if (logFileInfo.isArchived && !logFileInfo.isCompressed)
  78. {
  79. [self compressLogFile:logFileInfo];
  80. break;
  81. }
  82. i--;
  83. }
  84. upToDate = YES;
  85. }
  86. - (void)compressionDidSucceed:(DDLogFileInfo *)logFile
  87. {
  88. NSLogVerbose(@"CompressingLogFileManager: compressionDidSucceed: %@", logFile.fileName);
  89. self.isCompressing = NO;
  90. [self compressNextLogFile];
  91. }
  92. - (void)compressionDidFail:(DDLogFileInfo *)logFile
  93. {
  94. NSLogWarn(@"CompressingLogFileManager: compressionDidFail: %@", logFile.fileName);
  95. self.isCompressing = NO;
  96. // We should try the compression again, but after a short delay.
  97. //
  98. // If the compression failed there is probably some filesystem issue,
  99. // so flooding it with compression attempts is only going to make things worse.
  100. NSTimeInterval delay = (60 * 15); // 15 minutes
  101. [self performSelector:@selector(compressNextLogFile) withObject:nil afterDelay:delay];
  102. }
  103. - (void)didArchiveLogFile:(NSString *)logFilePath
  104. {
  105. NSLogVerbose(@"CompressingLogFileManager: didArchiveLogFile: %@", [logFilePath lastPathComponent]);
  106. // If all other log files have been compressed,
  107. // then we can get started right away.
  108. // Otherwise we should just wait for the current compression process to finish.
  109. if (upToDate)
  110. {
  111. [self compressLogFile:[DDLogFileInfo logFileWithPath:logFilePath]];
  112. }
  113. }
  114. - (void)didRollAndArchiveLogFile:(NSString *)logFilePath
  115. {
  116. NSLogVerbose(@"CompressingLogFileManager: didRollAndArchiveLogFile: %@", [logFilePath lastPathComponent]);
  117. // If all other log files have been compressed,
  118. // then we can get started right away.
  119. // Otherwise we should just wait for the current compression process to finish.
  120. if (upToDate)
  121. {
  122. [self compressLogFile:[DDLogFileInfo logFileWithPath:logFilePath]];
  123. }
  124. }
  125. - (void)backgroundThread_CompressLogFile:(DDLogFileInfo *)logFile
  126. {
  127. @autoreleasepool {
  128. NSLogInfo(@"CompressingLogFileManager: Compressing log file: %@", logFile.fileName);
  129. // Steps:
  130. // 1. Create a new file with the same fileName, but added "gzip" extension
  131. // 2. Open the new file for writing (output file)
  132. // 3. Open the given file for reading (input file)
  133. // 4. Setup zlib for gzip compression
  134. // 5. Read a chunk of the given file
  135. // 6. Compress the chunk
  136. // 7. Write the compressed chunk to the output file
  137. // 8. Repeat steps 5 - 7 until the input file is exhausted
  138. // 9. Close input and output file
  139. // 10. Teardown zlib
  140. // STEP 1
  141. NSString *inputFilePath = logFile.filePath;
  142. NSString *tempOutputFilePath = [logFile tempFilePathByAppendingPathExtension:@"gz"];
  143. #if TARGET_OS_IPHONE
  144. // We use the same protection as the original file. This means that it has the same security characteristics.
  145. // Also, if the app can run in the background, this means that it gets
  146. // NSFileProtectionCompleteUntilFirstUserAuthentication so that we can do this compression even with the
  147. // device locked. c.f. DDFileLogger.doesAppRunInBackground.
  148. NSString* protection = logFile.fileAttributes[NSFileProtectionKey];
  149. NSDictionary* attributes = protection == nil ? nil : @{NSFileProtectionKey: protection};
  150. [[NSFileManager defaultManager] createFileAtPath:tempOutputFilePath contents:nil attributes:attributes];
  151. #endif
  152. // STEP 2 & 3
  153. NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:inputFilePath];
  154. NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:tempOutputFilePath append:NO];
  155. [inputStream open];
  156. [outputStream open];
  157. // STEP 4
  158. z_stream strm;
  159. // Zero out the structure before (to be safe) before we start using it
  160. bzero(&strm, sizeof(strm));
  161. strm.zalloc = Z_NULL;
  162. strm.zfree = Z_NULL;
  163. strm.opaque = Z_NULL;
  164. strm.total_out = 0;
  165. // Compresssion Levels:
  166. // Z_NO_COMPRESSION
  167. // Z_BEST_SPEED
  168. // Z_BEST_COMPRESSION
  169. // Z_DEFAULT_COMPRESSION
  170. deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY);
  171. // Prepare our variables for steps 5-7
  172. //
  173. // inputDataLength : Total length of buffer that we will read file data into
  174. // outputDataLength : Total length of buffer that zlib will output compressed bytes into
  175. //
  176. // Note: The output buffer can be smaller than the input buffer because the
  177. // compressed/output data is smaller than the file/input data (obviously).
  178. //
  179. // inputDataSize : The number of bytes in the input buffer that have valid data to be compressed.
  180. //
  181. // Imagine compressing a tiny file that is actually smaller than our inputDataLength.
  182. // In this case only a portion of the input buffer would have valid file data.
  183. // The inputDataSize helps represent the portion of the buffer that is valid.
  184. //
  185. // Imagine compressing a huge file, but consider what happens when we get to the very end of the file.
  186. // The last read will likely only fill a portion of the input buffer.
  187. // The inputDataSize helps represent the portion of the buffer that is valid.
  188. NSUInteger inputDataLength = (1024 * 2); // 2 KB
  189. NSUInteger outputDataLength = (1024 * 1); // 1 KB
  190. NSMutableData *inputData = [NSMutableData dataWithLength:inputDataLength];
  191. NSMutableData *outputData = [NSMutableData dataWithLength:outputDataLength];
  192. NSUInteger inputDataSize = 0;
  193. BOOL done = YES;
  194. NSError* error = nil;
  195. do
  196. {
  197. @autoreleasepool {
  198. // STEP 5
  199. // Read data from the input stream into our input buffer.
  200. //
  201. // inputBuffer : pointer to where we want the input stream to copy bytes into
  202. // inputBufferLength : max number of bytes the input stream should read
  203. //
  204. // Recall that inputDataSize is the number of valid bytes that already exist in the
  205. // input buffer that still need to be compressed.
  206. // This value is usually zero, but may be larger if a previous iteration of the loop
  207. // was unable to compress all the bytes in the input buffer.
  208. //
  209. // For example, imagine that we ready 2K worth of data from the file in the last loop iteration,
  210. // but when we asked zlib to compress it all, zlib was only able to compress 1.5K of it.
  211. // We would still have 0.5K leftover that still needs to be compressed.
  212. // We want to make sure not to skip this important data.
  213. //
  214. // The [inputData mutableBytes] gives us a pointer to the beginning of the underlying buffer.
  215. // When we add inputDataSize we get to the proper offset within the buffer
  216. // at which our input stream can start copying bytes into without overwriting anything it shouldn't.
  217. const void *inputBuffer = [inputData mutableBytes] + inputDataSize;
  218. NSUInteger inputBufferLength = inputDataLength - inputDataSize;
  219. NSInteger readLength = [inputStream read:(uint8_t *)inputBuffer maxLength:inputBufferLength];
  220. if (readLength < 0) {
  221. error = [inputStream streamError];
  222. break;
  223. }
  224. NSLogVerbose(@"CompressingLogFileManager: Read %li bytes from file", (long)readLength);
  225. inputDataSize += readLength;
  226. // STEP 6
  227. // Ask zlib to compress our input buffer.
  228. // Tell it to put the compressed bytes into our output buffer.
  229. strm.next_in = (Bytef *)[inputData mutableBytes]; // Read from input buffer
  230. strm.avail_in = (uInt)inputDataSize; // as much as was read from file (plus leftovers).
  231. strm.next_out = (Bytef *)[outputData mutableBytes]; // Write data to output buffer
  232. strm.avail_out = (uInt)outputDataLength; // as much space as is available in the buffer.
  233. // When we tell zlib to compress our data,
  234. // it won't directly tell us how much data was processed.
  235. // Instead it keeps a running total of the number of bytes it has processed.
  236. // In other words, every iteration from the loop it increments its total values.
  237. // So to figure out how much data was processed in this iteration,
  238. // we fetch the totals before we ask it to compress data,
  239. // and then afterwards we subtract from the new totals.
  240. NSInteger prevTotalIn = strm.total_in;
  241. NSInteger prevTotalOut = strm.total_out;
  242. int flush = [inputStream hasBytesAvailable] ? Z_SYNC_FLUSH : Z_FINISH;
  243. deflate(&strm, flush);
  244. NSInteger inputProcessed = strm.total_in - prevTotalIn;
  245. NSInteger outputProcessed = strm.total_out - prevTotalOut;
  246. NSLogVerbose(@"CompressingLogFileManager: Total bytes uncompressed: %lu", (unsigned long)strm.total_in);
  247. NSLogVerbose(@"CompressingLogFileManager: Total bytes compressed: %lu", (unsigned long)strm.total_out);
  248. NSLogVerbose(@"CompressingLogFileManager: Compression ratio: %.1f%%",
  249. (1.0F - (float)(strm.total_out) / (float)(strm.total_in)) * 100);
  250. // STEP 7
  251. // Now write all compressed bytes to our output stream.
  252. //
  253. // It is theoretically possible that the write operation doesn't write everything we ask it to.
  254. // Although this is highly unlikely, we take precautions.
  255. // Also, we watch out for any errors (maybe the disk is full).
  256. NSUInteger totalWriteLength = 0;
  257. NSInteger writeLength = 0;
  258. do
  259. {
  260. const void *outputBuffer = [outputData mutableBytes] + totalWriteLength;
  261. NSUInteger outputBufferLength = outputProcessed - totalWriteLength;
  262. writeLength = [outputStream write:(const uint8_t *)outputBuffer maxLength:outputBufferLength];
  263. if (writeLength < 0)
  264. {
  265. error = [outputStream streamError];
  266. }
  267. else
  268. {
  269. totalWriteLength += writeLength;
  270. }
  271. } while((totalWriteLength < outputProcessed) && !error);
  272. // STEP 7.5
  273. //
  274. // We now have data in our input buffer that has already been compressed.
  275. // We want to remove all the processed data from the input buffer,
  276. // and we want to move any unprocessed data to the beginning of the buffer.
  277. //
  278. // If the amount processed is less than the valid buffer size, we have leftovers.
  279. NSUInteger inputRemaining = inputDataSize - inputProcessed;
  280. if (inputRemaining > 0)
  281. {
  282. void *inputDst = [inputData mutableBytes];
  283. void *inputSrc = [inputData mutableBytes] + inputProcessed;
  284. memmove(inputDst, inputSrc, inputRemaining);
  285. }
  286. inputDataSize = inputRemaining;
  287. // Are we done yet?
  288. done = ((flush == Z_FINISH) && (inputDataSize == 0));
  289. // STEP 8
  290. // Loop repeats until end of data (or unlikely error)
  291. } // end @autoreleasepool
  292. } while (!done && error == nil);
  293. // STEP 9
  294. [inputStream close];
  295. [outputStream close];
  296. // STEP 10
  297. deflateEnd(&strm);
  298. // We're done!
  299. // Report success or failure back to the logging thread/queue.
  300. if (error)
  301. {
  302. // Remove output file.
  303. // Our compression attempt failed.
  304. NSLogError(@"Compression of %@ failed: %@", inputFilePath, error);
  305. error = nil;
  306. BOOL ok = [[NSFileManager defaultManager] removeItemAtPath:tempOutputFilePath error:&error];
  307. if (!ok)
  308. NSLogError(@"Failed to clean up %@ after failed compression: %@", tempOutputFilePath, error);
  309. // Report failure to class via logging thread/queue
  310. dispatch_async([DDLog loggingQueue], ^{ @autoreleasepool {
  311. [self compressionDidFail:logFile];
  312. }});
  313. }
  314. else
  315. {
  316. // Remove original input file.
  317. // It will be replaced with the new compressed version.
  318. error = nil;
  319. BOOL ok = [[NSFileManager defaultManager] removeItemAtPath:inputFilePath error:&error];
  320. if (!ok)
  321. NSLogWarn(@"Warning: failed to remove original file %@ after compression: %@", inputFilePath, error);
  322. // Mark the compressed file as archived,
  323. // and then move it into its final destination.
  324. //
  325. // temp-log-ABC123.txt.gz -> log-ABC123.txt.gz
  326. //
  327. // The reason we were using the "temp-" prefix was so the file would not be
  328. // considered a log file while it was only partially complete.
  329. // Only files that begin with "log-" are considered log files.
  330. DDLogFileInfo *compressedLogFile = [DDLogFileInfo logFileWithPath:tempOutputFilePath];
  331. compressedLogFile.isArchived = YES;
  332. NSString *outputFileName = [logFile fileNameByAppendingPathExtension:@"gz"];
  333. [compressedLogFile renameFile:outputFileName];
  334. // Report success to class via logging thread/queue
  335. dispatch_async([DDLog loggingQueue], ^{ @autoreleasepool {
  336. [self compressionDidSucceed:compressedLogFile];
  337. }});
  338. }
  339. } // end @autoreleasepool
  340. }
  341. @end
  342. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  343. #pragma mark -
  344. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  345. @implementation DDLogFileInfo (Compressor)
  346. @dynamic isCompressed;
  347. - (BOOL)isCompressed
  348. {
  349. return [[[self fileName] pathExtension] isEqualToString:@"gz"];
  350. }
  351. - (NSString *)tempFilePathByAppendingPathExtension:(NSString *)newExt
  352. {
  353. // Example:
  354. //
  355. // Current File Name: "/full/path/to/log-ABC123.txt"
  356. //
  357. // newExt: "gzip"
  358. // result: "/full/path/to/temp-log-ABC123.txt.gzip"
  359. NSString *tempFileName = [NSString stringWithFormat:@"temp-%@", [self fileName]];
  360. NSString *newFileName = [tempFileName stringByAppendingPathExtension:newExt];
  361. NSString *fileDir = [[self filePath] stringByDeletingLastPathComponent];
  362. NSString *newFilePath = [fileDir stringByAppendingPathComponent:newFileName];
  363. return newFilePath;
  364. }
  365. - (NSString *)fileNameByAppendingPathExtension:(NSString *)newExt
  366. {
  367. // Example:
  368. //
  369. // Current File Name: "log-ABC123.txt"
  370. //
  371. // newExt: "gzip"
  372. // result: "log-ABC123.txt.gzip"
  373. NSString *fileNameExtension = [[self fileName] pathExtension];
  374. if ([fileNameExtension isEqualToString:newExt])
  375. {
  376. return [self fileName];
  377. }
  378. return [[self fileName] stringByAppendingPathExtension:newExt];
  379. }
  380. @end