FPRCPUGaugeCollector.m 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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/CPU/FPRCPUGaugeCollector.h"
  15. #import "FirebasePerformance/Sources/Gauges/CPU/FPRCPUGaugeCollector+Private.h"
  16. #import "FirebasePerformance/Sources/AppActivity/FPRSessionManager.h"
  17. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  18. #import "FirebasePerformance/Sources/FPRConsoleLogger.h"
  19. #import <assert.h>
  20. #import <mach/mach.h>
  21. @interface FPRCPUGaugeCollector ()
  22. /** @brief Timer property used for the frequency of CPU data collection. */
  23. @property(nonatomic) dispatch_source_t timerSource;
  24. /** @brief Gauge collector queue on which the gauge data collected. */
  25. @property(nonatomic) dispatch_queue_t gaugeCollectorQueue;
  26. /** @brief Boolean to see if the timer is active or paused. */
  27. @property(nonatomic) BOOL timerPaused;
  28. @end
  29. /**
  30. * Fetches the CPU metric and returns an instance of FPRCPUGaugeData.
  31. *
  32. * This implementation is inspired by the following references:
  33. * http://web.mit.edu/darwin/src/modules/xnu/osfmk/man/thread_basic_info.html
  34. * https://stackoverflow.com/a/8382889
  35. *
  36. * @return Instance of FPRCPUGaugeData.
  37. */
  38. FPRCPUGaugeData *fprCollectCPUMetric() {
  39. kern_return_t kernelReturnValue;
  40. mach_msg_type_number_t task_info_count;
  41. task_info_data_t taskInfo;
  42. thread_array_t threadList;
  43. mach_msg_type_number_t threadCount;
  44. task_basic_info_t taskBasicInfo;
  45. thread_basic_info_t threadBasicInfo;
  46. NSDate *collectionTime = [NSDate date];
  47. // Get the task info to find out the CPU time used by terminated threads.
  48. task_info_count = TASK_BASIC_INFO_COUNT;
  49. kernelReturnValue =
  50. task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)taskInfo, &task_info_count);
  51. if (kernelReturnValue != KERN_SUCCESS) {
  52. return nil;
  53. }
  54. taskBasicInfo = (task_basic_info_t)taskInfo;
  55. // Get the current set of threads and find their CPU time.
  56. kernelReturnValue = task_threads(mach_task_self(), &threadList, &threadCount);
  57. if (kernelReturnValue != KERN_SUCCESS) {
  58. return nil;
  59. }
  60. uint64_t totalUserTimeUsec =
  61. taskBasicInfo->user_time.seconds * USEC_PER_SEC + taskBasicInfo->user_time.microseconds;
  62. uint64_t totalSystemTimeUsec =
  63. taskBasicInfo->system_time.seconds * USEC_PER_SEC + taskBasicInfo->system_time.microseconds;
  64. thread_info_data_t threadInfo;
  65. mach_msg_type_number_t threadInfoCount;
  66. for (int i = 0; i < (int)threadCount; i++) {
  67. threadInfoCount = THREAD_INFO_MAX;
  68. kernelReturnValue =
  69. thread_info(threadList[i], THREAD_BASIC_INFO, (thread_info_t)threadInfo, &threadInfoCount);
  70. if (kernelReturnValue != KERN_SUCCESS) {
  71. return nil;
  72. }
  73. threadBasicInfo = (thread_basic_info_t)threadInfo;
  74. if (!(threadBasicInfo->flags & TH_FLAGS_IDLE)) {
  75. totalUserTimeUsec += threadBasicInfo->user_time.seconds * USEC_PER_SEC +
  76. threadBasicInfo->user_time.microseconds;
  77. totalSystemTimeUsec += threadBasicInfo->system_time.seconds * USEC_PER_SEC +
  78. threadBasicInfo->system_time.microseconds;
  79. }
  80. }
  81. kernelReturnValue =
  82. vm_deallocate(mach_task_self(), (vm_offset_t)threadList, threadCount * sizeof(thread_t));
  83. assert(kernelReturnValue == KERN_SUCCESS);
  84. FPRCPUGaugeData *gaugeData = [[FPRCPUGaugeData alloc] initWithCollectionTime:collectionTime
  85. systemTime:totalSystemTimeUsec
  86. userTime:totalUserTimeUsec];
  87. return gaugeData;
  88. }
  89. @implementation FPRCPUGaugeCollector
  90. - (instancetype)initWithDelegate:(id<FPRCPUGaugeCollectorDelegate>)delegate {
  91. self = [super init];
  92. if (self) {
  93. _delegate = delegate;
  94. _gaugeCollectorQueue =
  95. dispatch_queue_create("com.google.firebase.FPRCPUGaugeCollector", DISPATCH_QUEUE_SERIAL);
  96. _configurations = [FPRConfigurations sharedInstance];
  97. _timerPaused = YES;
  98. [self updateSamplingFrequencyForApplicationState:[FPRAppActivityTracker sharedInstance]
  99. .applicationState];
  100. }
  101. return self;
  102. }
  103. - (void)stopCollecting {
  104. if (self.timerPaused == NO) {
  105. dispatch_source_cancel(self.timerSource);
  106. self.timerPaused = YES;
  107. }
  108. }
  109. - (void)resumeCollecting {
  110. [self updateSamplingFrequencyForApplicationState:[FPRAppActivityTracker sharedInstance]
  111. .applicationState];
  112. }
  113. - (void)updateSamplingFrequencyForApplicationState:(FPRApplicationState)applicationState {
  114. uint32_t frequencyInMs = (applicationState == FPRApplicationStateBackground)
  115. ? [self.configurations cpuSamplingFrequencyInBackgroundInMS]
  116. : [self.configurations cpuSamplingFrequencyInForegroundInMS];
  117. [self captureCPUGaugeAtFrequency:frequencyInMs];
  118. }
  119. /**
  120. * Captures the CPU gauge at a defined frequency.
  121. *
  122. * @param frequencyInMs Frequency at which the CPU gauges are collected.
  123. */
  124. - (void)captureCPUGaugeAtFrequency:(uint32_t)frequencyInMs {
  125. [self stopCollecting];
  126. if (frequencyInMs > 0) {
  127. self.timerSource =
  128. dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.gaugeCollectorQueue);
  129. dispatch_source_set_timer(self.timerSource,
  130. dispatch_time(DISPATCH_TIME_NOW, frequencyInMs * NSEC_PER_MSEC),
  131. frequencyInMs * NSEC_PER_MSEC, (1ull * NSEC_PER_SEC) / 10);
  132. FPRCPUGaugeCollector __weak *weakSelf = self;
  133. dispatch_source_set_event_handler(weakSelf.timerSource, ^{
  134. FPRCPUGaugeCollector *strongSelf = weakSelf;
  135. if (strongSelf) {
  136. [strongSelf collectMetric];
  137. }
  138. });
  139. dispatch_resume(self.timerSource);
  140. self.timerPaused = NO;
  141. } else {
  142. FPRLogDebug(kFPRCPUCollection, @"CPU metric collection is disabled.");
  143. }
  144. }
  145. - (void)collectMetric {
  146. FPRCPUGaugeData *gaugeMetric = fprCollectCPUMetric();
  147. [self.delegate cpuGaugeCollector:self gaugeData:gaugeMetric];
  148. }
  149. @end