FPRClient.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. @import FirebaseSessions;
  34. @interface FPRClient () <FIRLibrary, FIRPerformanceProvider, FIRSessionsSubscriber>
  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. [FIRApp registerInternalLibrary:[FPRClient class]
  43. withName:@"fire-perf"
  44. withVersion:[NSString stringWithUTF8String:kFPRSDKVersion]];
  45. [FIRSessionsDependencies addDependencyWithName:FIRSessionsSubscriberNamePerformance];
  46. }
  47. #pragma mark - Component registration system
  48. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  49. FIRDependency *sessionsDep =
  50. [FIRDependency dependencyWithProtocol:@protocol(FIRSessionsProvider)];
  51. FIRComponentCreationBlock creationBlock =
  52. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  53. if (!container.app.isDefaultApp) {
  54. return nil;
  55. }
  56. id<FIRSessionsProvider> sessions = FIR_COMPONENT(FIRSessionsProvider, container);
  57. NSString *appName = container.app.name;
  58. FIRApp *app = [FIRApp appNamed:appName];
  59. FIROptions *options = app.options;
  60. NSError *error = nil;
  61. // Based on the environment variable SDK decides if events are dispatched to Autopush or Prod.
  62. // By default, events are sent to Prod.
  63. BOOL useAutoPush = NO;
  64. NSDictionary<NSString *, NSString *> *environment = [NSProcessInfo processInfo].environment;
  65. if (environment[@"FPR_AUTOPUSH_ENV"] != nil &&
  66. [environment[@"FPR_AUTOPUSH_ENV"] isEqualToString:@"1"]) {
  67. useAutoPush = YES;
  68. }
  69. FPRConfiguration *configuration = [FPRConfiguration configurationWithAppID:options.googleAppID
  70. APIKey:options.APIKey
  71. autoPush:useAutoPush];
  72. if (![[self sharedInstance] startWithConfiguration:configuration error:&error]) {
  73. FPRLogError(kFPRClientInitialize, @"Failed to initialize the client with error: %@.", error);
  74. }
  75. if (sessions) {
  76. FPRLogDebug(kFPRClientInitialize, @"Registering Sessions SDK subscription for session data");
  77. // Subscription should be made after the first call to [FPRClient sharedInstance] where
  78. // _configuration is initialized so that the sessions SDK can immediately get the data
  79. // collection state.
  80. [sessions registerWithSubscriber:[self sharedInstance]];
  81. }
  82. *isCacheable = YES;
  83. return [self sharedInstance];
  84. };
  85. FIRComponent *component =
  86. [FIRComponent componentWithProtocol:@protocol(FIRPerformanceProvider)
  87. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  88. dependencies:@[ sessionsDep ]
  89. creationBlock:creationBlock];
  90. return @[ component ];
  91. }
  92. + (FPRClient *)sharedInstance {
  93. static FPRClient *sharedInstance = nil;
  94. static dispatch_once_t token;
  95. dispatch_once(&token, ^{
  96. sharedInstance = [[FPRClient alloc] init];
  97. });
  98. return sharedInstance;
  99. }
  100. - (instancetype)init {
  101. self = [super init];
  102. if (self) {
  103. _instrumentation = [[FPRInstrumentation alloc] init];
  104. _swizzled = NO;
  105. _eventsQueue = dispatch_queue_create("com.google.perf.FPREventsQueue", DISPATCH_QUEUE_SERIAL);
  106. _eventsQueueGroup = dispatch_group_create();
  107. _configuration = [FPRConfigurations sharedInstance];
  108. _projectID = [FIROptions defaultOptions].projectID;
  109. _bundleID = [FIROptions defaultOptions].bundleID;
  110. }
  111. return self;
  112. }
  113. - (BOOL)startWithConfiguration:(FPRConfiguration *)config error:(NSError *__autoreleasing *)error {
  114. self.config = config;
  115. NSInteger logSource = [self.configuration logSource];
  116. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  117. // Create the Logger for the Perf SDK events to be sent to Google Data Transport.
  118. self.gdtLogger = [[FPRGDTLogger alloc] initWithLogSource:logSource];
  119. #ifdef TARGET_HAS_MOBILE_CONNECTIVITY
  120. // Create telephony network information object ahead of time to avoid runtime delays.
  121. FPRNetworkInfo();
  122. #endif
  123. // Update the configuration flags.
  124. [self.configuration update];
  125. [FPRClient cleanupClearcutCacheDirectory];
  126. });
  127. // Set up instrumentation.
  128. [self checkAndStartInstrumentation];
  129. self.configured = YES;
  130. static dispatch_once_t onceToken;
  131. dispatch_once(&onceToken, ^{
  132. FPRLogInfo(kFPRClientInitialize,
  133. @"Firebase Performance Monitoring is successfully initialized! In a minute, visit "
  134. @"the Firebase console to view your data: %@",
  135. [FPRConsoleURLGenerator generateDashboardURLWithProjectID:self.projectID
  136. bundleID:self.bundleID]);
  137. });
  138. return YES;
  139. }
  140. - (void)checkAndStartInstrumentation {
  141. BOOL instrumentationEnabled = self.configuration.isInstrumentationEnabled;
  142. if (instrumentationEnabled && !self.isSwizzled) {
  143. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupNetworkKey];
  144. [self.instrumentation registerInstrumentGroup:kFPRInstrumentationGroupUIKitKey];
  145. self.swizzled = YES;
  146. }
  147. }
  148. #pragma mark - Public methods
  149. - (void)logTrace:(FIRTrace *)trace {
  150. if (self.configured == NO) {
  151. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  152. trace.name);
  153. return;
  154. }
  155. if ([trace isCompleteAndValid]) {
  156. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  157. firebase_perf_v1_PerfMetric metric = FPRGetPerfMetricMessage(self.config.appID);
  158. FPRSetTraceMetric(&metric, FPRGetTraceMetric(trace));
  159. FPRSetApplicationProcessState(&metric,
  160. FPRApplicationProcessState(trace.backgroundTraceState));
  161. // Log the trace metric with its console URL.
  162. if ([trace.name hasPrefix:kFPRPrefixForScreenTraceName]) {
  163. FPRLogInfo(kFPRClientMetricLogged,
  164. @"Logging trace metric - %@ %.4fms. In a minute, visit the Firebase console to "
  165. @"view your data: %@",
  166. trace.name, metric.trace_metric.duration_us / 1000.0,
  167. [FPRConsoleURLGenerator generateScreenTraceURLWithProjectID:self.projectID
  168. bundleID:self.bundleID
  169. traceName:trace.name]);
  170. } else {
  171. FPRLogInfo(kFPRClientMetricLogged,
  172. @"Logging trace metric - %@ %.4fms. In a minute, visit the Firebase console to "
  173. @"view your data: %@",
  174. trace.name, metric.trace_metric.duration_us / 1000.0,
  175. [FPRConsoleURLGenerator generateCustomTraceURLWithProjectID:self.projectID
  176. bundleID:self.bundleID
  177. traceName:trace.name]);
  178. }
  179. [self processAndLogEvent:metric];
  180. });
  181. } else {
  182. FPRLogWarning(kFPRClientInvalidTrace, @"Invalid trace, skipping send.");
  183. }
  184. }
  185. - (void)logNetworkTrace:(nonnull FPRNetworkTrace *)trace {
  186. if (self.configured == NO) {
  187. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping trace event %@. Perf SDK not configured.",
  188. trace.URLRequest.URL.absoluteString);
  189. return;
  190. }
  191. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  192. if ([trace isValid]) {
  193. firebase_perf_v1_NetworkRequestMetric networkRequestMetric =
  194. FPRGetNetworkRequestMetric(trace);
  195. int64_t duration = networkRequestMetric.has_time_to_response_completed_us
  196. ? networkRequestMetric.time_to_response_completed_us
  197. : 0;
  198. NSString *responseCode = networkRequestMetric.has_http_response_code
  199. ? [@(networkRequestMetric.http_response_code) stringValue]
  200. : @"UNKNOWN";
  201. FPRLogInfo(kFPRClientMetricLogged,
  202. @"Logging network request trace - %@, Response code: %@, %.4fms",
  203. trace.trimmedURLString, responseCode, duration / 1000.0);
  204. firebase_perf_v1_PerfMetric metric = FPRGetPerfMetricMessage(self.config.appID);
  205. FPRSetNetworkRequestMetric(&metric, networkRequestMetric);
  206. FPRSetApplicationProcessState(&metric,
  207. FPRApplicationProcessState(trace.backgroundTraceState));
  208. [self processAndLogEvent:metric];
  209. }
  210. });
  211. }
  212. - (void)logGaugeMetric:(nonnull NSArray *)gaugeData forSessionId:(nonnull NSString *)sessionId {
  213. if (self.configured == NO) {
  214. FPRLogError(kFPRClientPerfNotConfigured, @"Dropping session event. Perf SDK not configured.");
  215. return;
  216. }
  217. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  218. firebase_perf_v1_PerfMetric metric = FPRGetPerfMetricMessage(self.config.appID);
  219. firebase_perf_v1_GaugeMetric gaugeMetric = firebase_perf_v1_GaugeMetric_init_default;
  220. if ((gaugeData != nil && gaugeData.count != 0) && (sessionId != nil && sessionId.length != 0)) {
  221. gaugeMetric = FPRGetGaugeMetric(gaugeData, sessionId);
  222. }
  223. FPRSetGaugeMetric(&metric, gaugeMetric);
  224. [self processAndLogEvent:metric];
  225. });
  226. // Check and update the sessionID if the session is running for too long.
  227. [[FPRSessionManager sharedInstance] stopGaugesIfRunningTooLong];
  228. }
  229. - (void)processAndLogEvent:(firebase_perf_v1_PerfMetric)event {
  230. BOOL tracingEnabled = self.configuration.isDataCollectionEnabled;
  231. if (!tracingEnabled) {
  232. FPRLogDebug(kFPRClientPerfNotConfigured, @"Dropping event since data collection is disabled.");
  233. return;
  234. }
  235. BOOL sdkEnabled = [self.configuration sdkEnabled];
  236. if (!sdkEnabled) {
  237. FPRLogInfo(kFPRClientSDKDisabled, @"Dropping event since Performance SDK is disabled.");
  238. return;
  239. }
  240. static dispatch_once_t onceToken;
  241. dispatch_once(&onceToken, ^{
  242. if (self.installations == nil) {
  243. // Delayed initialization of installations because FIRApp needs to be configured first.
  244. self.installations = [FIRInstallations installations];
  245. }
  246. });
  247. // Attempts to dispatch events if successfully retrieve installation ID.
  248. [self.installations
  249. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  250. if (error) {
  251. FPRLogError(kFPRClientInstanceIDNotAvailable, @"FIRInstallations error: %@",
  252. error.description);
  253. } else {
  254. dispatch_group_async(self.eventsQueueGroup, self.eventsQueue, ^{
  255. firebase_perf_v1_PerfMetric updatedEvent = event;
  256. updatedEvent.application_info.app_instance_id = FPREncodeString(identifier);
  257. [self.gdtLogger logEvent:updatedEvent];
  258. });
  259. }
  260. }];
  261. }
  262. #pragma mark - Clearcut log directory removal methods
  263. + (void)cleanupClearcutCacheDirectory {
  264. NSString *logDirectoryPath = [FPRClient logDirectoryPath];
  265. if (logDirectoryPath != nil) {
  266. BOOL logDirectoryExists = [[NSFileManager defaultManager] fileExistsAtPath:logDirectoryPath];
  267. if (logDirectoryExists) {
  268. NSError *directoryError = nil;
  269. [[NSFileManager defaultManager] removeItemAtPath:logDirectoryPath error:&directoryError];
  270. if (directoryError) {
  271. FPRLogDebug(kFPRClientTempDirectory,
  272. @"Failed to delete the stale log directory at path: %@ with error: %@.",
  273. logDirectoryPath, directoryError);
  274. }
  275. }
  276. }
  277. }
  278. + (NSString *)logDirectoryPath {
  279. static NSString *cacheDir;
  280. static NSString *fireperfCacheDir;
  281. static dispatch_once_t onceToken;
  282. dispatch_once(&onceToken, ^{
  283. cacheDir =
  284. [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  285. if (!cacheDir) {
  286. fireperfCacheDir = nil;
  287. } else {
  288. fireperfCacheDir = [cacheDir stringByAppendingPathComponent:@"firebase_perf_logging"];
  289. }
  290. });
  291. return fireperfCacheDir;
  292. }
  293. #pragma mark - Unswizzling, use only for unit tests
  294. - (void)disableInstrumentation {
  295. [self.instrumentation deregisterInstrumentGroup:kFPRInstrumentationGroupNetworkKey];
  296. [self.instrumentation deregisterInstrumentGroup:kFPRInstrumentationGroupUIKitKey];
  297. self.swizzled = NO;
  298. [self.configuration setInstrumentationEnabled:NO];
  299. }
  300. #pragma mark - FIRSessionsSubscriber
  301. - (void)onSessionChanged:(FIRSessionDetails *_Nonnull)session {
  302. [[FPRSessionManager sharedInstance] updateSessionId:session.sessionId];
  303. }
  304. - (BOOL)isDataCollectionEnabled {
  305. return self.configuration.isDataCollectionEnabled;
  306. }
  307. - (FIRSessionsSubscriberName)sessionsSubscriberName {
  308. return FIRSessionsSubscriberNamePerformance;
  309. }
  310. @end