FPRGaugeManager.m 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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) 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. [self prepareAndDispatchGaugeData];
  99. self.currentSessionId = sessionId;
  100. if (self.gaugeCollectionEnabled) {
  101. if ((gauges & FPRGaugeCPU) == FPRGaugeCPU) {
  102. self.cpuGaugeCollector = [[FPRCPUGaugeCollector alloc] initWithDelegate:self];
  103. }
  104. if ((gauges & FPRGaugeMemory) == FPRGaugeMemory) {
  105. self.memoryGaugeCollector = [[FPRMemoryGaugeCollector alloc] initWithDelegate:self];
  106. }
  107. self.activeGauges = self.activeGauges | gauges;
  108. }
  109. }
  110. - (void)stopCollectingGauges:(FPRGauges)gauges {
  111. if ((gauges & FPRGaugeCPU) == FPRGaugeCPU) {
  112. self.cpuGaugeCollector = nil;
  113. }
  114. if ((gauges & FPRGaugeMemory) == FPRGaugeMemory) {
  115. self.memoryGaugeCollector = nil;
  116. }
  117. self.activeGauges = self.activeGauges & ~(gauges);
  118. [self prepareAndDispatchGaugeData];
  119. }
  120. - (void)collectAllGauges {
  121. if (self.cpuGaugeCollector) {
  122. [self.cpuGaugeCollector collectMetric];
  123. }
  124. if (self.memoryGaugeCollector) {
  125. [self.memoryGaugeCollector collectMetric];
  126. }
  127. }
  128. - (void)dispatchMetric:(id)gaugeMetric {
  129. // If the gauge metric is of type CPU, then dispatch only if CPU collection is enabled.
  130. if ([gaugeMetric isKindOfClass:[FPRCPUGaugeData class]] &&
  131. ((self.activeGauges & FPRGaugeCPU) == FPRGaugeCPU)) {
  132. [self addGaugeData:gaugeMetric];
  133. }
  134. // If the gauge metric is of type memory, then dispatch only if memory collection is enabled.
  135. if ([gaugeMetric isKindOfClass:[FPRMemoryGaugeData class]] &&
  136. ((self.activeGauges & FPRGaugeMemory) == FPRGaugeMemory)) {
  137. [self addGaugeData:gaugeMetric];
  138. }
  139. }
  140. #pragma mark - Utils
  141. - (void)prepareAndDispatchGaugeData {
  142. NSArray *currentBatch = self.gaugeData;
  143. NSString *currentSessionId = self.currentSessionId;
  144. self.gaugeData = [[NSMutableArray alloc] init];
  145. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  146. if (currentBatch.count > 0) {
  147. [[FPRClient sharedInstance] logGaugeMetric:currentBatch forSessionId:currentSessionId];
  148. FPRLogDebug(kFPRGaugeManagerDataCollected, @"Logging %lu gauge metrics.",
  149. (unsigned long)currentBatch.count);
  150. }
  151. });
  152. }
  153. /**
  154. * Adds the gauge to the batch and decide on when to dispatch the events to Google Data Transport.
  155. *
  156. * @param gaugeData Gauge data received from the collectors.
  157. */
  158. - (void)addGaugeData:(id)gaugeData {
  159. dispatch_async(self.gaugeDataProtectionQueue, ^{
  160. if (gaugeData) {
  161. [self.gaugeData addObject:gaugeData];
  162. if (self.gaugeData.count >= kGaugeDataBatchSize) {
  163. [self prepareAndDispatchGaugeData];
  164. }
  165. }
  166. });
  167. }
  168. #pragma mark - FPRCPUGaugeCollectorDelegate methods
  169. - (void)cpuGaugeCollector:(FPRCPUGaugeCollector *)collector gaugeData:(FPRCPUGaugeData *)gaugeData {
  170. [self addGaugeData:gaugeData];
  171. }
  172. #pragma mark - FPRMemoryGaugeCollectorDelegate methods
  173. - (void)memoryGaugeCollector:(FPRMemoryGaugeCollector *)collector
  174. gaugeData:(FPRMemoryGaugeData *)gaugeData {
  175. [self addGaugeData:gaugeData];
  176. }
  177. @end