FPRClient.m 13 KB

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