FPRGaugeManager.m 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "FirebasePerformance/Sources/Gauges/FPRGaugeManager.h"
  15. #import "FirebasePerformance/Sources/Gauges/FPRGaugeManager+Private.h"
  16. #import "FirebasePerformance/Sources/Common/FPRDiagnostics.h"
  17. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  18. #import "FirebasePerformance/Sources/FPRClient.h"
  19. #import "FirebasePerformance/Sources/Gauges/CPU/FPRCPUGaugeCollector.h"
  20. #import "FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeCollector.h"
  21. #import <UIKit/UIKit.h>
  22. // Number of gauge data information after which that gets flushed to Google Data Transport.
  23. NSInteger const kGaugeDataBatchSize = 25;
  24. @interface FPRGaugeManager () <FPRCPUGaugeCollectorDelegate, FPRMemoryGaugeCollectorDelegate>
  25. /** @brief List of gauges that are currently being actively captured. */
  26. @property(nonatomic, readwrite) FPRGauges activeGauges;
  27. /** @brief List of gauge information collected. Intentionally this is not a typed collection. Gauge
  28. * data could be CPU Gauge data or Memory gauge data.
  29. */
  30. @property(nonatomic) NSMutableArray *gaugeData;
  31. /** @brief Currently active sessionID. */
  32. @property(nonatomic, readwrite, copy) NSString *currentSessionId;
  33. @end
  34. @implementation FPRGaugeManager
  35. + (instancetype)sharedInstance {
  36. static FPRGaugeManager *instance = nil;
  37. static dispatch_once_t onceToken;
  38. dispatch_once(&onceToken, ^{
  39. instance = [[FPRGaugeManager alloc] initWithGauges:FPRGaugeNone];
  40. });
  41. return instance;
  42. }
  43. - (instancetype)initWithGauges:(FPRGauges)gauges {
  44. self = [super init];
  45. if (self) {
  46. _activeGauges = FPRGaugeNone;
  47. _gaugeData = [[NSMutableArray alloc] init];
  48. _gaugeDataProtectionQueue =
  49. dispatch_queue_create("com.google.perf.gaugeManager.gaugeData", DISPATCH_QUEUE_SERIAL);
  50. _isColdStart = YES;
  51. [self startAppActivityTracking];
  52. }
  53. return self;
  54. }
  55. - (void)dealloc {
  56. [[NSNotificationCenter defaultCenter] removeObserver:self
  57. name:UIApplicationDidBecomeActiveNotification
  58. object:[UIApplication sharedApplication]];
  59. [[NSNotificationCenter defaultCenter] removeObserver:self
  60. name:UIApplicationWillResignActiveNotification
  61. object:[UIApplication sharedApplication]];
  62. }
  63. /**
  64. * Starts tracking the application state changes.
  65. */
  66. - (void)startAppActivityTracking {
  67. [[NSNotificationCenter defaultCenter] addObserver:self
  68. selector:@selector(appStateChanged:)
  69. name:UIApplicationDidBecomeActiveNotification
  70. object:[UIApplication sharedApplication]];
  71. [[NSNotificationCenter defaultCenter] addObserver:self
  72. selector:@selector(appStateChanged:)
  73. name:UIApplicationWillResignActiveNotification
  74. object:[UIApplication sharedApplication]];
  75. }
  76. - (void)appStateChanged:(NSNotification *)notification {
  77. FPRApplicationState applicationState = [FPRAppActivityTracker sharedInstance].applicationState;
  78. [self.cpuGaugeCollector updateSamplingFrequencyForApplicationState:applicationState];
  79. [self.memoryGaugeCollector updateSamplingFrequencyForApplicationState:applicationState];
  80. self.isColdStart = NO;
  81. }
  82. #pragma mark - Implementation methods
  83. - (BOOL)gaugeCollectionEnabled {
  84. // Allow gauge collection to happen during cold start. During dispatch time, we do another check
  85. // to make sure if gauge collection is enabled. This is to accomodate gauge metric collection
  86. // during app_start scenario.
  87. if (self.isColdStart) {
  88. return YES;
  89. }
  90. // Check if the SDK is enabled to collect gauge data.
  91. BOOL sdkEnabled = [[FPRConfigurations sharedInstance] sdkEnabled];
  92. if (!sdkEnabled) {
  93. return NO;
  94. }
  95. return [FPRConfigurations sharedInstance].isDataCollectionEnabled;
  96. }
  97. - (void)startCollectingGauges:(FPRGauges)gauges forSessionId:(NSString *)sessionId {
  98. // Dispatch the already available gauge data with old sessionId.
  99. [self prepareAndDispatchCollectedGaugeDataWithSessionId:self.currentSessionId];
  100. self.currentSessionId = sessionId;
  101. if (self.gaugeCollectionEnabled) {
  102. if ((gauges & FPRGaugeCPU) == FPRGaugeCPU) {
  103. self.cpuGaugeCollector = [[FPRCPUGaugeCollector alloc] initWithDelegate:self];
  104. }
  105. if ((gauges & FPRGaugeMemory) == FPRGaugeMemory) {
  106. self.memoryGaugeCollector = [[FPRMemoryGaugeCollector alloc] initWithDelegate:self];
  107. }
  108. self.activeGauges = self.activeGauges | gauges;
  109. }
  110. }
  111. - (void)stopCollectingGauges:(FPRGauges)gauges {
  112. if ((gauges & FPRGaugeCPU) == FPRGaugeCPU) {
  113. self.cpuGaugeCollector = nil;
  114. }
  115. if ((gauges & FPRGaugeMemory) == FPRGaugeMemory) {
  116. self.memoryGaugeCollector = nil;
  117. }
  118. self.activeGauges = self.activeGauges & ~(gauges);
  119. // Flush out all the already collected gauge metrics
  120. [self prepareAndDispatchCollectedGaugeDataWithSessionId:self.currentSessionId];
  121. }
  122. - (void)collectAllGauges {
  123. if (self.cpuGaugeCollector) {
  124. [self.cpuGaugeCollector collectMetric];
  125. }
  126. if (self.memoryGaugeCollector) {
  127. [self.memoryGaugeCollector collectMetric];
  128. }
  129. }
  130. - (void)dispatchMetric:(id)gaugeMetric {
  131. // If the gauge metric is of type CPU, then dispatch only if CPU collection is enabled.
  132. if ([gaugeMetric isKindOfClass:[FPRCPUGaugeData class]] &&
  133. ((self.activeGauges & FPRGaugeCPU) == FPRGaugeCPU)) {
  134. [self addGaugeData:gaugeMetric];
  135. }
  136. // If the gauge metric is of type memory, then dispatch only if memory collection is enabled.
  137. if ([gaugeMetric isKindOfClass:[FPRMemoryGaugeData class]] &&
  138. ((self.activeGauges & FPRGaugeMemory) == FPRGaugeMemory)) {
  139. [self addGaugeData:gaugeMetric];
  140. }
  141. }
  142. #pragma mark - Utils
  143. - (void)prepareAndDispatchCollectedGaugeDataWithSessionId:(nullable NSString *)sessionId {
  144. dispatch_async(self.gaugeDataProtectionQueue, ^{
  145. NSArray *dispatchGauges = [self.gaugeData copy];
  146. self.gaugeData = [[NSMutableArray alloc] init];
  147. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  148. if (dispatchGauges.count > 0 && sessionId != nil) {
  149. [[FPRClient sharedInstance] logGaugeMetric:dispatchGauges forSessionId:sessionId];
  150. FPRLogDebug(kFPRGaugeManagerDataCollected, @"Logging %lu gauge metrics.",
  151. (unsigned long)dispatchGauges.count);
  152. }
  153. });
  154. });
  155. }
  156. /**
  157. * Adds the gauge to the batch and decide on when to dispatch the events to Google Data Transport.
  158. *
  159. * @param gauge Gauge data received from the collectors.
  160. */
  161. - (void)addGaugeData:(id)gauge {
  162. dispatch_async(self.gaugeDataProtectionQueue, ^{
  163. if (gauge) {
  164. [self.gaugeData addObject:gauge];
  165. if (self.gaugeData.count >= kGaugeDataBatchSize) {
  166. [self prepareAndDispatchCollectedGaugeDataWithSessionId:self.currentSessionId];
  167. }
  168. }
  169. });
  170. }
  171. #pragma mark - FPRCPUGaugeCollectorDelegate methods
  172. - (void)cpuGaugeCollector:(FPRCPUGaugeCollector *)collector gaugeData:(FPRCPUGaugeData *)gaugeData {
  173. [self addGaugeData:gaugeData];
  174. }
  175. #pragma mark - FPRMemoryGaugeCollectorDelegate methods
  176. - (void)memoryGaugeCollector:(FPRMemoryGaugeCollector *)collector
  177. gaugeData:(FPRMemoryGaugeData *)gaugeData {
  178. [self addGaugeData:gaugeData];
  179. }
  180. @end