FPRClient.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. // Create telephony network information object ahead of time to avoid runtime delays.
  102. FPRNetworkInfo();
  103. // Update the configuration flags.
  104. [self.configuration update];
  105. [FPRClient cleanupClearcutCacheDirectory];
  106. });
  107. // Set up instrumentation.
  108. [self checkAndStartInstrumentation];
  109. self.configured = YES;
  110. return YES;
  111. }
  112. - (void)checkAndStartInstrumentation {
  113. BOOL instrumentationEnabled = self.configuration.isInstrumentationEnabled;
  114. if (instrumentationEnabled && !self.isSwizzled) {
  115. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupNetworkKey];
  116. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupUIKitKey];
  117. self.swizzled = YES;
  118. }
  119. }
  120. #pragma mark - Public methods
  121. - (void)logTrace:(FIRTrace *)trace {
  122. if (self.configured == NO) {
  123. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  124. trace.name);
  125. return;
  126. }
  127. if ([trace isCompleteAndValid]) {
  128. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  129. FPRMSGPerfMetric *metric = FPRGetPerfMetricMessage(self.config.appID);
  130. metric.traceMetric = FPRGetTraceMetric(trace);
  131. metric.applicationInfo.applicationProcessState =
  132. FPRApplicationProcessState(trace.backgroundTraceState);
  133. FPRLogDebug(kFPRClientMetricLogged, @"Logging trace metric - %@ %.4fms",
  134. metric.traceMetric.name, metric.traceMetric.durationUs / 1000.0);
  135. [self processAndLogEvent:metric];
  136. });
  137. } else {
  138. FPRLogWarning(kFPRClientInvalidTrace, @"Invalid trace, skipping send.");
  139. }
  140. }
  141. - (void)logNetworkTrace:(nonnull FPRNetworkTrace *)trace {
  142. if (self.configured == NO) {
  143. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  144. trace.URLRequest.URL.absoluteString);
  145. return;
  146. }
  147. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  148. FPRMSGNetworkRequestMetric *networkRequestMetric = FPRGetNetworkRequestMetric(trace);
  149. if (networkRequestMetric) {
  150. int64_t duration = networkRequestMetric.hasTimeToResponseCompletedUs
  151. ? networkRequestMetric.timeToResponseCompletedUs
  152. : 0;
  153. NSString *responseCode = networkRequestMetric.hasHTTPResponseCode
  154. ? [@(networkRequestMetric.HTTPResponseCode) stringValue]
  155. : @"UNKNOWN";
  156. FPRLogDebug(kFPRClientMetricLogged,
  157. @"Logging network request trace - %@, Response code: %@, %.4fms",
  158. networkRequestMetric.URL, responseCode, duration / 1000.0);
  159. FPRMSGPerfMetric *metric = FPRGetPerfMetricMessage(self.config.appID);
  160. metric.networkRequestMetric = networkRequestMetric;
  161. metric.applicationInfo.applicationProcessState =
  162. FPRApplicationProcessState(trace.backgroundTraceState);
  163. [self processAndLogEvent:metric];
  164. }
  165. });
  166. }
  167. - (void)logGaugeMetric:(nonnull NSArray *)gaugeData forSessionId:(nonnull NSString *)sessionId {
  168. if (self.configured == NO) {
  169. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping session event. Perf SDK not configured.");
  170. return;
  171. }
  172. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  173. FPRMSGPerfMetric *metric = FPRGetPerfMetricMessage(self.config.appID);
  174. FPRMSGGaugeMetric *gaugeMetric = FPRGetGaugeMetric(gaugeData, sessionId);
  175. metric.gaugeMetric = gaugeMetric;
  176. [self processAndLogEvent:metric];
  177. });
  178. // Check and update the sessionID if the session is running for too long.
  179. [[FPRSessionManager sharedInstance] renewSessionIdIfRunningTooLong];
  180. }
  181. - (void)processAndLogEvent:(FPRMSGPerfMetric *)event {
  182. BOOL tracingEnabled = self.configuration.isDataCollectionEnabled;
  183. if (!tracingEnabled) {
  184. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping event since data collection is disabled.");
  185. return;
  186. }
  187. BOOL sdkEnabled = [self.configuration sdkEnabled];
  188. if (!sdkEnabled) {
  189. FPRLogInfo(kFPRClientSDKDisabled, @"Dropping event since Performance SDK is disabled.");
  190. return;
  191. }
  192. static dispatch_once_t onceToken;
  193. dispatch_once(&onceToken, ^{
  194. if (self.installations == nil) {
  195. // Delayed initialization of installations because FIRApp needs to be configured first.
  196. self.installations = [FIRInstallations installations];
  197. }
  198. });
  199. // Attempts to dispatch events if successfully retrieve installation ID.
  200. [self.installations
  201. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  202. if (error) {
  203. FPRLogError(kFPRClientInstanceIDNotAvailable, @"FIRInstallations error: %@",
  204. error.description);
  205. } else {
  206. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  207. event.applicationInfo.appInstanceId = identifier;
  208. [self.gdtLogger logEvent:event];
  209. });
  210. }
  211. }];
  212. }
  213. #pragma mark - Clearcut log directory removal methods
  214. + (void)cleanupClearcutCacheDirectory {
  215. NSString *logDirectoryPath = [FPRClient logDirectoryPath];
  216. if (logDirectoryPath != nil) {
  217. BOOL logDirectoryExists = [[NSFileManager defaultManager] fileExistsAtPath:logDirectoryPath];
  218. if (logDirectoryExists) {
  219. NSError *directoryError = nil;
  220. [[NSFileManager defaultManager] removeItemAtPath:logDirectoryPath error:&directoryError];
  221. if (directoryError) {
  222. FPRLogDebug(kFPRClientTempDirectory,
  223. @"Failed to delete the stale log directory at path: %@ with error: %@.",
  224. logDirectoryPath, directoryError);
  225. }
  226. }
  227. }
  228. }
  229. + (NSString *)logDirectoryPath {
  230. static NSString *cacheDir;
  231. static NSString *fireperfCacheDir;
  232. static dispatch_once_t onceToken;
  233. dispatch_once(&onceToken, ^{
  234. cacheDir =
  235. [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  236. if (!cacheDir) {
  237. fireperfCacheDir = nil;
  238. } else {
  239. fireperfCacheDir = [cacheDir stringByAppendingPathComponent:@"firebase_perf_logging"];
  240. }
  241. });
  242. return fireperfCacheDir;
  243. }
  244. #pragma mark - Unswizzling, use only for unit tests
  245. - (void)disableInstrumentation {
  246. [self.instrumentation deregisterInstrumentGroup:kFPRInstrumentationGroupNetworkKey];
  247. [self.instrumentation deregisterInstrumentGroup:kFPRInstrumentationGroupUIKitKey];
  248. self.swizzled = NO;
  249. [self.configuration setInstrumentationEnabled:NO];
  250. }
  251. @end