FPRClient.m 11 KB

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