FPRClient.m 13 KB

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