FPRGaugeManager.m 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  25. @interface FPRGaugeManager () <FPRCPUGaugeCollectorDelegate, FPRMemoryGaugeCollectorDelegate>
  26. /** @brief List of gauges that are currently being actively captured. */
  27. @property(nonatomic, readwrite) FPRGauges activeGauges;
  28. /** @brief List of gauge information collected. Intentionally this is not a typed collection. Gauge
  29. * data could be CPU Gauge data or Memory gauge data.
  30. */
  31. @property(nonatomic) NSMutableArray *gaugeData;
  32. /** @brief Currently active sessionID. */
  33. @property(nonatomic, readwrite, copy) NSString *currentSessionId;
  34. @end
  35. @implementation FPRGaugeManager
  36. + (instancetype)sharedInstance {
  37. static FPRGaugeManager *instance = nil;
  38. static dispatch_once_t onceToken;
  39. dispatch_once(&onceToken, ^{
  40. instance = [[FPRGaugeManager alloc] initWithGauges:FPRGaugeNone];
  41. });
  42. return instance;
  43. }
  44. - (instancetype)initWithGauges:(FPRGauges)gauges {
  45. self = [super init];
  46. if (self) {
  47. _activeGauges = FPRGaugeNone;
  48. _gaugeData = [[NSMutableArray alloc] init];
  49. _gaugeDataProtectionQueue =
  50. dispatch_queue_create("com.google.perf.gaugeManager.gaugeData", DISPATCH_QUEUE_SERIAL);
  51. _isColdStart = YES;
  52. [self startAppActivityTracking];
  53. }
  54. return self;
  55. }
  56. - (void)dealloc {
  57. [[NSNotificationCenter defaultCenter] removeObserver:self
  58. name:UIApplicationDidBecomeActiveNotification
  59. object:[UIApplication sharedApplication]];
  60. [[NSNotificationCenter defaultCenter] removeObserver:self
  61. name:UIApplicationWillResignActiveNotification
  62. object:[UIApplication sharedApplication]];
  63. }
  64. /**
  65. * Starts tracking the application state changes.
  66. */
  67. - (void)startAppActivityTracking {
  68. [[NSNotificationCenter defaultCenter] addObserver:self
  69. selector:@selector(appStateChanged:)
  70. name:UIApplicationDidBecomeActiveNotification
  71. object:[UIApplication sharedApplication]];
  72. [[NSNotificationCenter defaultCenter] addObserver:self
  73. selector:@selector(appStateChanged:)
  74. name:UIApplicationWillResignActiveNotification
  75. object:[UIApplication sharedApplication]];
  76. }
  77. - (void)appStateChanged:(NSNotification *)notification {
  78. FPRApplicationState applicationState = [FPRAppActivityTracker sharedInstance].applicationState;
  79. [self.cpuGaugeCollector updateSamplingFrequencyForApplicationState:applicationState];
  80. [self.memoryGaugeCollector updateSamplingFrequencyForApplicationState:applicationState];
  81. self.isColdStart = NO;
  82. }
  83. #pragma mark - Implementation methods
  84. - (BOOL)gaugeCollectionEnabled {
  85. // Allow gauge collection to happen during cold start. During dispatch time, we do another check
  86. // to make sure if gauge collection is enabled. This is to accomodate gauge metric collection
  87. // during app_start scenario.
  88. if (self.isColdStart) {
  89. return YES;
  90. }
  91. // Check if the SDK is enabled to collect gauge data.
  92. BOOL sdkEnabled = [[FPRConfigurations sharedInstance] sdkEnabled];
  93. if (!sdkEnabled) {
  94. return NO;
  95. }
  96. return [FPRConfigurations sharedInstance].isDataCollectionEnabled;
  97. }
  98. - (void)startCollectingGauges:(FPRGauges)gauges forSessionId:(NSString *)sessionId {
  99. // Dispatch the already available gauge data with old sessionId.
  100. [self prepareAndDispatchCollectedGaugeDataWithSessionId:self.currentSessionId];
  101. self.currentSessionId = sessionId;
  102. if (self.gaugeCollectionEnabled) {
  103. if ((gauges & FPRGaugeCPU) == FPRGaugeCPU) {
  104. self.cpuGaugeCollector = [[FPRCPUGaugeCollector alloc] initWithDelegate:self];
  105. }
  106. if ((gauges & FPRGaugeMemory) == FPRGaugeMemory) {
  107. self.memoryGaugeCollector = [[FPRMemoryGaugeCollector alloc] initWithDelegate:self];
  108. }
  109. self.activeGauges = self.activeGauges | gauges;
  110. }
  111. }
  112. - (void)stopCollectingGauges:(FPRGauges)gauges {
  113. if ((gauges & FPRGaugeCPU) == FPRGaugeCPU) {
  114. self.cpuGaugeCollector = nil;
  115. }
  116. if ((gauges & FPRGaugeMemory) == FPRGaugeMemory) {
  117. self.memoryGaugeCollector = nil;
  118. }
  119. self.activeGauges = self.activeGauges & ~(gauges);
  120. // Flush out all the already collected gauge metrics
  121. [self prepareAndDispatchCollectedGaugeDataWithSessionId:self.currentSessionId];
  122. }
  123. - (void)collectAllGauges {
  124. if (self.cpuGaugeCollector) {
  125. [self.cpuGaugeCollector collectMetric];
  126. }
  127. if (self.memoryGaugeCollector) {
  128. [self.memoryGaugeCollector collectMetric];
  129. }
  130. }
  131. - (void)dispatchMetric:(id)gaugeMetric {
  132. // If the gauge metric is of type CPU, then dispatch only if CPU collection is enabled.
  133. if ([gaugeMetric isKindOfClass:[FPRCPUGaugeData class]] &&
  134. ((self.activeGauges & FPRGaugeCPU) == FPRGaugeCPU)) {
  135. [self addGaugeData:gaugeMetric];
  136. }
  137. // If the gauge metric is of type memory, then dispatch only if memory collection is enabled.
  138. if ([gaugeMetric isKindOfClass:[FPRMemoryGaugeData class]] &&
  139. ((self.activeGauges & FPRGaugeMemory) == FPRGaugeMemory)) {
  140. [self addGaugeData:gaugeMetric];
  141. }
  142. }
  143. #pragma mark - Utils
  144. - (void)prepareAndDispatchCollectedGaugeDataWithSessionId:(nullable NSString *)sessionId {
  145. dispatch_async(self.gaugeDataProtectionQueue, ^{
  146. NSArray *dispatchGauges = [self.gaugeData copy];
  147. self.gaugeData = [[NSMutableArray alloc] init];
  148. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  149. if (dispatchGauges.count > 0 && sessionId != nil) {
  150. [[FPRClient sharedInstance] logGaugeMetric:dispatchGauges forSessionId:sessionId];
  151. FPRLogInfo(kFPRGaugeManagerDataCollected, @"Logging %lu gauge metrics.",
  152. (unsigned long)dispatchGauges.count);
  153. }
  154. });
  155. });
  156. }
  157. /**
  158. * Adds the gauge to the batch and decide on when to dispatch the events to Google Data Transport.
  159. *
  160. * @param gauge Gauge data received from the collectors.
  161. */
  162. - (void)addGaugeData:(id)gauge {
  163. dispatch_async(self.gaugeDataProtectionQueue, ^{
  164. if (gauge) {
  165. [self.gaugeData addObject:gauge];
  166. if (self.gaugeData.count >= kGaugeDataBatchSize) {
  167. [self prepareAndDispatchCollectedGaugeDataWithSessionId:self.currentSessionId];
  168. }
  169. }
  170. });
  171. }
  172. #pragma mark - FPRCPUGaugeCollectorDelegate methods
  173. - (void)cpuGaugeCollector:(FPRCPUGaugeCollector *)collector gaugeData:(FPRCPUGaugeData *)gaugeData {
  174. [self addGaugeData:gaugeData];
  175. }
  176. #pragma mark - FPRMemoryGaugeCollectorDelegate methods
  177. - (void)memoryGaugeCollector:(FPRMemoryGaugeCollector *)collector
  178. gaugeData:(FPRMemoryGaugeData *)gaugeData {
  179. [self addGaugeData:gaugeData];
  180. }
  181. @end