FPRClient.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/FPRNanoPbUtils.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/FirebasePerformance/FIRPerformance.h"
  32. #import "FirebaseCore/Extension/FirebaseCoreInternal.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. _projectID = [FIROptions defaultOptions].projectID;
  95. _bundleID = [FIROptions defaultOptions].bundleID;
  96. }
  97. return self;
  98. }
  99. - (BOOL)startWithConfiguration:(FPRConfiguration *)config error:(NSError *__autoreleasing *)error {
  100. self.config = config;
  101. NSInteger logSource = [self.configuration logSource];
  102. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  103. // Create the Logger for the Perf SDK events to be sent to Google Data Transport.
  104. self.gdtLogger = [[FPRGDTLogger alloc] initWithLogSource:logSource];
  105. #ifdef TARGET_HAS_MOBILE_CONNECTIVITY
  106. // Create telephony network information object ahead of time to avoid runtime delays.
  107. FPRNetworkInfo();
  108. #endif
  109. // Update the configuration flags.
  110. [self.configuration update];
  111. [FPRClient cleanupClearcutCacheDirectory];
  112. });
  113. // Set up instrumentation.
  114. [self checkAndStartInstrumentation];
  115. self.configured = YES;
  116. static dispatch_once_t onceToken;
  117. dispatch_once(&onceToken, ^{
  118. FPRLogInfo(kFPRClientInitialize,
  119. @"Firebase Performance Monitoring is successfully initialized! In a minute, visit "
  120. @"the Firebase console to view your data: %@",
  121. [FPRConsoleURLGenerator generateDashboardURLWithProjectID:self.projectID
  122. bundleID:self.bundleID]);
  123. });
  124. return YES;
  125. }
  126. - (void)checkAndStartInstrumentation {
  127. BOOL instrumentationEnabled = self.configuration.isInstrumentationEnabled;
  128. if (instrumentationEnabled && !self.isSwizzled) {
  129. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupNetworkKey];
  130. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupUIKitKey];
  131. self.swizzled = YES;
  132. }
  133. }
  134. #pragma mark - Public methods
  135. - (void)logTrace:(FIRTrace *)trace {
  136. if (self.configured == NO) {
  137. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  138. trace.name);
  139. return;
  140. }
  141. if ([trace isCompleteAndValid]) {
  142. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  143. firebase_perf_v1_PerfMetric metric = FPRGetPerfMetricMessage(self.config.appID);
  144. FPRSetTraceMetric(&metric, FPRGetTraceMetric(trace));
  145. FPRSetApplicationProcessState(&metric,
  146. FPRApplicationProcessState(trace.backgroundTraceState));
  147. // Log the trace metric with its console URL.
  148. if ([trace.name hasPrefix:kFPRPrefixForScreenTraceName]) {
  149. FPRLogInfo(kFPRClientMetricLogged,
  150. @"Logging trace metric - %@ %.4fms. In a minute, visit the Firebase console to "
  151. @"view your data: %@",
  152. trace.name, metric.trace_metric.duration_us / 1000.0,
  153. [FPRConsoleURLGenerator generateScreenTraceURLWithProjectID:self.projectID
  154. bundleID:self.bundleID
  155. traceName:trace.name]);
  156. } else {
  157. FPRLogInfo(kFPRClientMetricLogged,
  158. @"Logging trace metric - %@ %.4fms. In a minute, visit the Firebase console to "
  159. @"view your data: %@",
  160. trace.name, metric.trace_metric.duration_us / 1000.0,
  161. [FPRConsoleURLGenerator generateCustomTraceURLWithProjectID:self.projectID
  162. bundleID:self.bundleID
  163. traceName:trace.name]);
  164. }
  165. [self processAndLogEvent:metric];
  166. });
  167. } else {
  168. FPRLogWarning(kFPRClientInvalidTrace, @"Invalid trace, skipping send.");
  169. }
  170. }
  171. - (void)logNetworkTrace:(nonnull FPRNetworkTrace *)trace {
  172. if (self.configured == NO) {
  173. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  174. trace.URLRequest.URL.absoluteString);
  175. return;
  176. }
  177. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  178. if ([trace isValid]) {
  179. firebase_perf_v1_NetworkRequestMetric networkRequestMetric =
  180. FPRGetNetworkRequestMetric(trace);
  181. int64_t duration = networkRequestMetric.has_time_to_response_completed_us
  182. ? networkRequestMetric.time_to_response_completed_us
  183. : 0;
  184. NSString *responseCode = networkRequestMetric.has_http_response_code
  185. ? [@(networkRequestMetric.http_response_code) stringValue]
  186. : @"UNKNOWN";
  187. FPRLogInfo(kFPRClientMetricLogged,
  188. @"Logging network request trace - %@, Response code: %@, %.4fms",
  189. trace.trimmedURLString, responseCode, duration / 1000.0);
  190. firebase_perf_v1_PerfMetric metric = FPRGetPerfMetricMessage(self.config.appID);
  191. FPRSetNetworkRequestMetric(&metric, networkRequestMetric);
  192. FPRSetApplicationProcessState(&metric,
  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. firebase_perf_v1_PerfMetric metric = FPRGetPerfMetricMessage(self.config.appID);
  205. firebase_perf_v1_GaugeMetric gaugeMetric = firebase_perf_v1_GaugeMetric_init_default;
  206. if ((gaugeData != nil && gaugeData.count != 0) && (sessionId != nil && sessionId.length != 0)) {
  207. gaugeMetric = FPRGetGaugeMetric(gaugeData, sessionId);
  208. }
  209. FPRSetGaugeMetric(&metric, gaugeMetric);
  210. [self processAndLogEvent:metric];
  211. });
  212. // Check and update the sessionID if the session is running for too long.
  213. [[FPRSessionManager sharedInstance] renewSessionIdIfRunningTooLong];
  214. }
  215. - (void)processAndLogEvent:(firebase_perf_v1_PerfMetric)event {
  216. BOOL tracingEnabled = self.configuration.isDataCollectionEnabled;
  217. if (!tracingEnabled) {
  218. FPRLogDebug(kFPRClientPerfNotConfigured, @"Dropping event since data collection is disabled.");
  219. return;
  220. }
  221. BOOL sdkEnabled = [self.configuration sdkEnabled];
  222. if (!sdkEnabled) {
  223. FPRLogInfo(kFPRClientSDKDisabled, @"Dropping event since Performance SDK is disabled.");
  224. return;
  225. }
  226. static dispatch_once_t onceToken;
  227. dispatch_once(&onceToken, ^{
  228. if (self.installations == nil) {
  229. // Delayed initialization of installations because FIRApp needs to be configured first.
  230. self.installations = [FIRInstallations installations];
  231. }
  232. });
  233. // Attempts to dispatch events if successfully retrieve installation ID.
  234. [self.installations
  235. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  236. if (error) {
  237. FPRLogError(kFPRClientInstanceIDNotAvailable, @"FIRInstallations error: %@",
  238. error.description);
  239. } else {
  240. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  241. firebase_perf_v1_PerfMetric updatedEvent = event;
  242. updatedEvent.application_info.app_instance_id = FPREncodeString(identifier);
  243. [self.gdtLogger logEvent:updatedEvent];
  244. });
  245. }
  246. }];
  247. }
  248. #pragma mark - Clearcut log directory removal methods
  249. + (void)cleanupClearcutCacheDirectory {
  250. NSString *logDirectoryPath = [FPRClient logDirectoryPath];
  251. if (logDirectoryPath != nil) {
  252. BOOL logDirectoryExists = [[NSFileManager defaultManager] fileExistsAtPath:logDirectoryPath];
  253. if (logDirectoryExists) {
  254. NSError *directoryError = nil;
  255. [[NSFileManager defaultManager] removeItemAtPath:logDirectoryPath error:&directoryError];
  256. if (directoryError) {
  257. FPRLogDebug(kFPRClientTempDirectory,
  258. @"Failed to delete the stale log directory at path: %@ with error: %@.",
  259. logDirectoryPath, directoryError);
  260. }
  261. }
  262. }
  263. }
  264. + (NSString *)logDirectoryPath {
  265. static NSString *cacheDir;
  266. static NSString *fireperfCacheDir;
  267. static dispatch_once_t onceToken;
  268. dispatch_once(&onceToken, ^{
  269. cacheDir =
  270. [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  271. if (!cacheDir) {
  272. fireperfCacheDir = nil;
  273. } else {
  274. fireperfCacheDir = [cacheDir stringByAppendingPathComponent:@"firebase_perf_logging"];
  275. }
  276. });
  277. return fireperfCacheDir;
  278. }
  279. #pragma mark - Unswizzling, use only for unit tests
  280. - (void)disableInstrumentation {
  281. [self.instrumentation deregisterInstrumentGroup:kFPRInstrumentationGroupNetworkKey];
  282. [self.instrumentation deregisterInstrumentGroup:kFPRInstrumentationGroupUIKitKey];
  283. self.swizzled = NO;
  284. [self.configuration setInstrumentationEnabled:NO];
  285. }
  286. @end