FPRClient.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. NSString *appName = appInfoDict[kFIRAppNameKey];
  46. FIRApp *app = [FIRApp appNamed:appName];
  47. FIROptions *options = app.options;
  48. NSError *error = nil;
  49. // Based on the environment variable SDK decides if events are dispatchd to Autopush or Prod.
  50. // By default, events are sent to Prod.
  51. BOOL useAutoPush = NO;
  52. NSDictionary<NSString *, NSString *> *environment = [NSProcessInfo processInfo].environment;
  53. if (environment[@"FPR_AUTOPUSH_ENV"] != nil &&
  54. [environment[@"FPR_AUTOPUSH_ENV"] isEqualToString:@"1"]) {
  55. useAutoPush = YES;
  56. }
  57. FPRConfiguration *configuration = [FPRConfiguration configurationWithAppID:options.googleAppID
  58. APIKey:options.APIKey
  59. autoPush:useAutoPush];
  60. if (![[self sharedInstance] startWithConfiguration:configuration error:&error]) {
  61. FPRLogError(kFPRClientInitialize, @"Failed to initialize the client with error: %@.", error);
  62. }
  63. [notificationCenter removeObserver:listener];
  64. listener = nil;
  65. };
  66. // Register the Perf library for Firebase Core tracking.
  67. [FIRApp registerLibrary:@"fire-perf" // From go/firebase-sdk-platform-info
  68. withVersion:[NSString stringWithUTF8String:kFPRSDKVersion]];
  69. listener = [notificationCenter addObserverForName:kFIRAppReadyToConfigureSDKNotification
  70. object:[FIRApp class]
  71. queue:nil
  72. usingBlock:observerBlock];
  73. }
  74. + (FPRClient *)sharedInstance {
  75. static FPRClient *sharedInstance = nil;
  76. static dispatch_once_t token;
  77. dispatch_once(&token, ^{
  78. sharedInstance = [[FPRClient alloc] init];
  79. });
  80. return sharedInstance;
  81. }
  82. - (instancetype)init {
  83. self = [super init];
  84. if (self) {
  85. _instrumentation = [[FPRInstrumentation alloc] init];
  86. _swizzled = NO;
  87. _eventsQueue = dispatch_queue_create("com.google.perf.FPREventsQueue", DISPATCH_QUEUE_SERIAL);
  88. _eventsQueueGroup = dispatch_group_create();
  89. _configuration = [FPRConfigurations sharedInstance];
  90. _projectID = [FIROptions defaultOptions].projectID;
  91. _bundleID = [FIROptions defaultOptions].bundleID;
  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 = [[FPRGDTLogger alloc] initWithLogSource:logSource];
  101. #ifdef TARGET_HAS_MOBILE_CONNECTIVITY
  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. static dispatch_once_t onceToken;
  113. dispatch_once(&onceToken, ^{
  114. FPRLogInfo(kFPRClientInitialize,
  115. @"Firebase Performance Monitoring is successfully initialized! In a minute, visit "
  116. @"the Firebase console to view your data: %@",
  117. [FPRConsoleURLGenerator generateDashboardURLWithProjectID:self.projectID
  118. bundleID:self.bundleID]);
  119. });
  120. return YES;
  121. }
  122. - (void)checkAndStartInstrumentation {
  123. BOOL instrumentationEnabled = self.configuration.isInstrumentationEnabled;
  124. if (instrumentationEnabled && !self.isSwizzled) {
  125. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupNetworkKey];
  126. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupUIKitKey];
  127. self.swizzled = YES;
  128. }
  129. }
  130. #pragma mark - Public methods
  131. - (void)logTrace:(FIRTrace *)trace {
  132. if (self.configured == NO) {
  133. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  134. trace.name);
  135. return;
  136. }
  137. if ([trace isCompleteAndValid]) {
  138. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  139. firebase_perf_v1_PerfMetric metric = FPRGetPerfMetricMessage(self.config.appID);
  140. FPRSetTraceMetric(&metric, FPRGetTraceMetric(trace));
  141. FPRSetApplicationProcessState(&metric,
  142. FPRApplicationProcessState(trace.backgroundTraceState));
  143. // Log the trace metric with its console URL.
  144. if ([trace.name hasPrefix:kFPRPrefixForScreenTraceName]) {
  145. FPRLogInfo(kFPRClientMetricLogged,
  146. @"Logging trace metric - %@ %.4fms. In a minute, visit the Firebase console to "
  147. @"view your data: %@",
  148. trace.name, metric.trace_metric.duration_us / 1000.0,
  149. [FPRConsoleURLGenerator generateScreenTraceURLWithProjectID:self.projectID
  150. bundleID:self.bundleID
  151. traceName:trace.name]);
  152. } else {
  153. FPRLogInfo(kFPRClientMetricLogged,
  154. @"Logging trace metric - %@ %.4fms. In a minute, visit the Firebase console to "
  155. @"view your data: %@",
  156. trace.name, metric.trace_metric.duration_us / 1000.0,
  157. [FPRConsoleURLGenerator generateCustomTraceURLWithProjectID:self.projectID
  158. bundleID:self.bundleID
  159. traceName:trace.name]);
  160. }
  161. [self processAndLogEvent:metric];
  162. });
  163. } else {
  164. FPRLogWarning(kFPRClientInvalidTrace, @"Invalid trace, skipping send.");
  165. }
  166. }
  167. - (void)logNetworkTrace:(nonnull FPRNetworkTrace *)trace {
  168. if (self.configured == NO) {
  169. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  170. trace.URLRequest.URL.absoluteString);
  171. return;
  172. }
  173. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  174. if ([trace isValid]) {
  175. firebase_perf_v1_NetworkRequestMetric networkRequestMetric =
  176. FPRGetNetworkRequestMetric(trace);
  177. int64_t duration = networkRequestMetric.has_time_to_response_completed_us
  178. ? networkRequestMetric.time_to_response_completed_us
  179. : 0;
  180. NSString *responseCode = networkRequestMetric.has_http_response_code
  181. ? [@(networkRequestMetric.http_response_code) stringValue]
  182. : @"UNKNOWN";
  183. FPRLogInfo(kFPRClientMetricLogged,
  184. @"Logging network request trace - %@, Response code: %@, %.4fms",
  185. trace.trimmedURLString, responseCode, duration / 1000.0);
  186. firebase_perf_v1_PerfMetric metric = FPRGetPerfMetricMessage(self.config.appID);
  187. FPRSetNetworkRequestMetric(&metric, networkRequestMetric);
  188. FPRSetApplicationProcessState(&metric,
  189. FPRApplicationProcessState(trace.backgroundTraceState));
  190. [self processAndLogEvent:metric];
  191. }
  192. });
  193. }
  194. - (void)logGaugeMetric:(nonnull NSArray *)gaugeData forSessionId:(nonnull NSString *)sessionId {
  195. if (self.configured == NO) {
  196. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping session event. Perf SDK not configured.");
  197. return;
  198. }
  199. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  200. firebase_perf_v1_PerfMetric metric = FPRGetPerfMetricMessage(self.config.appID);
  201. firebase_perf_v1_GaugeMetric gaugeMetric = firebase_perf_v1_GaugeMetric_init_default;
  202. if ((gaugeData != nil && gaugeData.count != 0) && (sessionId != nil && sessionId.length != 0)) {
  203. gaugeMetric = FPRGetGaugeMetric(gaugeData, sessionId);
  204. }
  205. FPRSetGaugeMetric(&metric, gaugeMetric);
  206. [self processAndLogEvent:metric];
  207. });
  208. // Check and update the sessionID if the session is running for too long.
  209. [[FPRSessionManager sharedInstance] renewSessionIdIfRunningTooLong];
  210. }
  211. - (void)processAndLogEvent:(firebase_perf_v1_PerfMetric)event {
  212. BOOL tracingEnabled = self.configuration.isDataCollectionEnabled;
  213. if (!tracingEnabled) {
  214. FPRLogDebug(kFPRClientPerfNotConfigured, @"Dropping event since data collection is disabled.");
  215. return;
  216. }
  217. BOOL sdkEnabled = [self.configuration sdkEnabled];
  218. if (!sdkEnabled) {
  219. FPRLogInfo(kFPRClientSDKDisabled, @"Dropping event since Performance SDK is disabled.");
  220. return;
  221. }
  222. static dispatch_once_t onceToken;
  223. dispatch_once(&onceToken, ^{
  224. if (self.installations == nil) {
  225. // Delayed initialization of installations because FIRApp needs to be configured first.
  226. self.installations = [FIRInstallations installations];
  227. }
  228. });
  229. // Attempts to dispatch events if successfully retrieve installation ID.
  230. [self.installations
  231. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  232. if (error) {
  233. FPRLogError(kFPRClientInstanceIDNotAvailable, @"FIRInstallations error: %@",
  234. error.description);
  235. } else {
  236. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  237. firebase_perf_v1_PerfMetric updatedEvent = event;
  238. updatedEvent.application_info.app_instance_id = FPREncodeString(identifier);
  239. [self.gdtLogger logEvent:updatedEvent];
  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