FPRClient.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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/FPRClient.h"
  15. #import "FirebasePerformance/Sources/FPRClient+Private.h"
  16. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  17. #import "FirebasePerformance/Sources/AppActivity/FPRScreenTraceTracker.h"
  18. #import "FirebasePerformance/Sources/AppActivity/FPRSessionManager+Private.h"
  19. #import "FirebasePerformance/Sources/AppActivity/FPRTraceBackgroundActivityTracker.h"
  20. #import "FirebasePerformance/Sources/Common/FPRConstants.h"
  21. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  22. #import "FirebasePerformance/Sources/Configurations/FPRRemoteConfigFlags.h"
  23. #import "FirebasePerformance/Sources/FPRConsoleLogger.h"
  24. #import "FirebasePerformance/Sources/FPRProtoUtils.h"
  25. #import "FirebasePerformance/Sources/Instrumentation/FPRInstrumentation.h"
  26. #import "FirebasePerformance/Sources/Loggers/FPRGDTCCLogger.h"
  27. #import "FirebasePerformance/Sources/Timer/FIRTrace+Internal.h"
  28. #import "FirebasePerformance/Sources/Timer/FIRTrace+Private.h"
  29. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  30. #import "FirebasePerformance/ProtoSupport/PerfMetric.pbobjc.h"
  31. @interface FPRClient ()
  32. /** The original configuration object used to initialize the client. */
  33. @property(nonatomic, strong) FPRConfiguration *config;
  34. /** The object that manages all automatic class instrumentation. */
  35. @property(nonatomic) FPRInstrumentation *instrumentation;
  36. @end
  37. @implementation FPRClient
  38. + (void)load {
  39. __weak NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  40. __block id listener;
  41. void (^observerBlock)(NSNotification *) = ^(NSNotification *aNotification) {
  42. NSDictionary *appInfoDict = aNotification.userInfo;
  43. NSNumber *isDefaultApp = appInfoDict[kFIRAppIsDefaultAppKey];
  44. if (![isDefaultApp boolValue]) {
  45. return;
  46. }
  47. NSString *appName = appInfoDict[kFIRAppNameKey];
  48. FIRApp *app = [FIRApp appNamed:appName];
  49. FIROptions *options = app.options;
  50. NSError *error = nil;
  51. // Based on the environment variable SDK decides if events are dispatchd to Autopush or Prod.
  52. // By default, events are sent to Prod.
  53. BOOL useAutoPush = NO;
  54. NSDictionary<NSString *, NSString *> *environment = [NSProcessInfo processInfo].environment;
  55. if (environment[@"FPR_AUTOPUSH_ENV"] != nil &&
  56. [environment[@"FPR_AUTOPUSH_ENV"] isEqualToString:@"1"]) {
  57. useAutoPush = YES;
  58. }
  59. FPRConfiguration *configuration = [FPRConfiguration configurationWithAppID:options.googleAppID
  60. APIKey:options.APIKey
  61. autoPush:useAutoPush];
  62. if (![[self sharedInstance] startWithConfiguration:configuration error:&error]) {
  63. FPRLogError(kFPRClientInitialize, @"Failed to initialize the client with error: %@.", error);
  64. }
  65. [notificationCenter removeObserver:listener];
  66. listener = nil;
  67. };
  68. // Register the Perf library for Firebase Core tracking.
  69. [FIRApp registerLibrary:@"fire-perf" // From go/firebase-sdk-platform-info
  70. withVersion:[NSString stringWithUTF8String:kFPRSDKVersion]];
  71. listener = [notificationCenter addObserverForName:kFIRAppReadyToConfigureSDKNotification
  72. object:[FIRApp class]
  73. queue:nil
  74. usingBlock:observerBlock];
  75. }
  76. + (FPRClient *)sharedInstance {
  77. static FPRClient *sharedInstance = nil;
  78. static dispatch_once_t token;
  79. dispatch_once(&token, ^{
  80. sharedInstance = [[FPRClient alloc] init];
  81. });
  82. return sharedInstance;
  83. }
  84. - (instancetype)init {
  85. self = [super init];
  86. if (self) {
  87. _instrumentation = [[FPRInstrumentation alloc] init];
  88. _swizzled = NO;
  89. _eventsQueue = dispatch_queue_create("com.google.perf.FPREventsQueue", DISPATCH_QUEUE_SERIAL);
  90. _eventsQueueGroup = dispatch_group_create();
  91. _configuration = [FPRConfigurations sharedInstance];
  92. }
  93. return self;
  94. }
  95. - (BOOL)startWithConfiguration:(FPRConfiguration *)config error:(NSError *__autoreleasing *)error {
  96. self.config = config;
  97. NSInteger logSource = [self.configuration logSource];
  98. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  99. // Create the Logger for the Perf SDK events to be sent to Google Data Transport.
  100. self.gdtLogger = [[FPRGDTCCLogger alloc] initWithLogSource:logSource];
  101. #if __has_include("CoreTelephony/CTTelephonyNetworkInfo.h")
  102. // Create telephony network information object ahead of time to avoid runtime delays.
  103. FPRNetworkInfo();
  104. #endif
  105. // Update the configuration flags.
  106. [self.configuration update];
  107. [FPRClient cleanupClearcutCacheDirectory];
  108. });
  109. // Set up instrumentation.
  110. [self checkAndStartInstrumentation];
  111. self.configured = YES;
  112. return YES;
  113. }
  114. - (void)checkAndStartInstrumentation {
  115. BOOL instrumentationEnabled = self.configuration.isInstrumentationEnabled;
  116. if (instrumentationEnabled && !self.isSwizzled) {
  117. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupNetworkKey];
  118. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupUIKitKey];
  119. self.swizzled = YES;
  120. }
  121. }
  122. #pragma mark - Public methods
  123. - (void)logTrace:(FIRTrace *)trace {
  124. if (self.configured == NO) {
  125. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  126. trace.name);
  127. return;
  128. }
  129. if ([trace isCompleteAndValid]) {
  130. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  131. FPRMSGPerfMetric *metric = FPRGetPerfMetricMessage(self.config.appID);
  132. metric.traceMetric = FPRGetTraceMetric(trace);
  133. metric.applicationInfo.applicationProcessState =
  134. FPRApplicationProcessState(trace.backgroundTraceState);
  135. FPRLogDebug(kFPRClientMetricLogged, @"Logging trace metric - %@ %.4fms",
  136. metric.traceMetric.name, metric.traceMetric.durationUs / 1000.0);
  137. [self processAndLogEvent:metric];
  138. });
  139. } else {
  140. FPRLogWarning(kFPRClientInvalidTrace, @"Invalid trace, skipping send.");
  141. }
  142. }
  143. - (void)logNetworkTrace:(nonnull FPRNetworkTrace *)trace {
  144. if (self.configured == NO) {
  145. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  146. trace.URLRequest.URL.absoluteString);
  147. return;
  148. }
  149. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  150. FPRMSGNetworkRequestMetric *networkRequestMetric = FPRGetNetworkRequestMetric(trace);
  151. if (networkRequestMetric) {
  152. int64_t duration = networkRequestMetric.hasTimeToResponseCompletedUs
  153. ? networkRequestMetric.timeToResponseCompletedUs
  154. : 0;
  155. NSString *responseCode = networkRequestMetric.hasHTTPResponseCode
  156. ? [@(networkRequestMetric.HTTPResponseCode) stringValue]
  157. : @"UNKNOWN";
  158. FPRLogDebug(kFPRClientMetricLogged,
  159. @"Logging network request trace - %@, Response code: %@, %.4fms",
  160. networkRequestMetric.URL, responseCode, duration / 1000.0);
  161. FPRMSGPerfMetric *metric = FPRGetPerfMetricMessage(self.config.appID);
  162. metric.networkRequestMetric = networkRequestMetric;
  163. metric.applicationInfo.applicationProcessState =
  164. FPRApplicationProcessState(trace.backgroundTraceState);
  165. [self processAndLogEvent:metric];
  166. }
  167. });
  168. }
  169. - (void)logGaugeMetric:(nonnull NSArray *)gaugeData forSessionId:(nonnull NSString *)sessionId {
  170. if (self.configured == NO) {
  171. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping session event. Perf SDK not configured.");
  172. return;
  173. }
  174. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  175. FPRMSGPerfMetric *metric = FPRGetPerfMetricMessage(self.config.appID);
  176. FPRMSGGaugeMetric *gaugeMetric = FPRGetGaugeMetric(gaugeData, sessionId);
  177. metric.gaugeMetric = gaugeMetric;
  178. [self processAndLogEvent:metric];
  179. });
  180. // Check and update the sessionID if the session is running for too long.
  181. [[FPRSessionManager sharedInstance] renewSessionIdIfRunningTooLong];
  182. }
  183. - (void)processAndLogEvent:(FPRMSGPerfMetric *)event {
  184. BOOL tracingEnabled = self.configuration.isDataCollectionEnabled;
  185. if (!tracingEnabled) {
  186. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping event since data collection is disabled.");
  187. return;
  188. }
  189. BOOL sdkEnabled = [self.configuration sdkEnabled];
  190. if (!sdkEnabled) {
  191. FPRLogInfo(kFPRClientSDKDisabled, @"Dropping event since Performance SDK is disabled.");
  192. return;
  193. }
  194. static dispatch_once_t onceToken;
  195. dispatch_once(&onceToken, ^{
  196. if (self.installations == nil) {
  197. // Delayed initialization of installations because FIRApp needs to be configured first.
  198. self.installations = [FIRInstallations installations];
  199. }
  200. });
  201. // Attempts to dispatch events if successfully retrieve installation ID.
  202. [self.installations
  203. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  204. if (error) {
  205. FPRLogError(kFPRClientInstanceIDNotAvailable, @"FIRInstallations error: %@",
  206. error.description);
  207. } else {
  208. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  209. event.applicationInfo.appInstanceId = identifier;
  210. [self.gdtLogger logEvent:event];
  211. });
  212. }
  213. }];
  214. }
  215. #pragma mark - Clearcut log directory removal methods
  216. + (void)cleanupClearcutCacheDirectory {
  217. NSString *logDirectoryPath = [FPRClient logDirectoryPath];
  218. if (logDirectoryPath != nil) {
  219. BOOL logDirectoryExists = [[NSFileManager defaultManager] fileExistsAtPath:logDirectoryPath];
  220. if (logDirectoryExists) {
  221. NSError *directoryError = nil;
  222. [[NSFileManager defaultManager] removeItemAtPath:logDirectoryPath error:&directoryError];
  223. if (directoryError) {
  224. FPRLogDebug(kFPRClientTempDirectory,
  225. @"Failed to delete the stale log directory at path: %@ with error: %@.",
  226. logDirectoryPath, directoryError);
  227. }
  228. }
  229. }
  230. }
  231. + (NSString *)logDirectoryPath {
  232. static NSString *cacheDir;
  233. static NSString *fireperfCacheDir;
  234. static dispatch_once_t onceToken;
  235. dispatch_once(&onceToken, ^{
  236. cacheDir =
  237. [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  238. if (!cacheDir) {
  239. fireperfCacheDir = nil;
  240. } else {
  241. fireperfCacheDir = [cacheDir stringByAppendingPathComponent:@"firebase_perf_logging"];
  242. }
  243. });
  244. return fireperfCacheDir;
  245. }
  246. #pragma mark - Unswizzling, use only for unit tests
  247. - (void)disableInstrumentation {
  248. [self.instrumentation deregisterInstrumentGroup:kFPRInstrumentationGroupNetworkKey];
  249. [self.instrumentation deregisterInstrumentGroup:kFPRInstrumentationGroupUIKitKey];
  250. self.swizzled = NO;
  251. [self.configuration setInstrumentationEnabled:NO];
  252. }
  253. @end