1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.adservices.service.measurement.reporting; 18 19 import static com.android.adservices.service.measurement.util.JobLockHolder.Type.EVENT_REPORTING; 20 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_BACKGROUND_JOBS_EXECUTION_REPORTED__EXECUTION_RESULT_CODE__SKIP_FOR_KILL_SWITCH_ON; 21 import static com.android.adservices.spe.AdServicesJobInfo.MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB; 22 23 import android.app.job.JobInfo; 24 import android.app.job.JobParameters; 25 import android.app.job.JobScheduler; 26 import android.app.job.JobService; 27 import android.content.ComponentName; 28 import android.content.Context; 29 30 import com.android.adservices.LogUtil; 31 import com.android.adservices.LoggerFactory; 32 import com.android.adservices.concurrency.AdServicesExecutors; 33 import com.android.adservices.data.measurement.DatastoreManagerFactory; 34 import com.android.adservices.service.AdServicesConfig; 35 import com.android.adservices.service.Flags; 36 import com.android.adservices.service.FlagsFactory; 37 import com.android.adservices.service.common.compat.ServiceCompatUtils; 38 import com.android.adservices.service.measurement.util.JobLockHolder; 39 import com.android.adservices.service.stats.AdServicesLoggerImpl; 40 import com.android.adservices.spe.AdServicesJobServiceLogger; 41 import com.android.internal.annotations.VisibleForTesting; 42 43 import com.google.android.libraries.mobiledatadownload.internal.AndroidTimeSource; 44 import com.google.common.util.concurrent.ListeningExecutorService; 45 46 import java.util.concurrent.Future; 47 48 /** 49 * Fallback service for scheduling reporting jobs (runs less frequently than the main service 50 * without a network type requirement). The actual job execution logic is part of {@link 51 * EventReportingJobHandler} 52 */ 53 public final class EventFallbackReportingJobService extends JobService { 54 private static final int MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID = 55 MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB.getJobId(); 56 57 private static final ListeningExecutorService sBlockingExecutor = 58 AdServicesExecutors.getBlockingExecutor(); 59 60 private Future mExecutorFuture; 61 62 @Override onStartJob(JobParameters params)63 public boolean onStartJob(JobParameters params) { 64 // Always ensure that the first thing this job does is check if it should be running, and 65 // cancel itself if it's not supposed to be. 66 if (ServiceCompatUtils.shouldDisableExtServicesJobOnTPlus(this)) { 67 LogUtil.d( 68 "Disabling EventFallbackReportingJobService job because it's running in" 69 + " ExtServices on T+"); 70 return skipAndCancelBackgroundJob(params, /* skipReason=*/ 0, /* doRecord=*/ false); 71 } 72 73 AdServicesJobServiceLogger.getInstance() 74 .recordOnStartJob(MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID); 75 76 if (FlagsFactory.getFlags().getMeasurementJobEventFallbackReportingKillSwitch()) { 77 LoggerFactory.getMeasurementLogger() 78 .e("EventFallbackReportingJobService Job is disabled"); 79 return skipAndCancelBackgroundJob( 80 params, 81 AD_SERVICES_BACKGROUND_JOBS_EXECUTION_REPORTED__EXECUTION_RESULT_CODE__SKIP_FOR_KILL_SWITCH_ON, 82 /* doRecord=*/ true); 83 } 84 85 LoggerFactory.getMeasurementLogger().d("EventFallbackReportingJobService.onStartJob"); 86 mExecutorFuture = 87 sBlockingExecutor.submit( 88 () -> { 89 processPendingReports(); 90 91 AdServicesJobServiceLogger.getInstance() 92 .recordJobFinished( 93 MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID, 94 /* isSuccessful= */ true, 95 /* shouldRetry= */ false); 96 97 jobFinished(params, /* wantsReschedule= */ false); 98 }); 99 return true; 100 } 101 102 @VisibleForTesting processPendingReports()103 void processPendingReports() { 104 JobLockHolder.getInstance(EVENT_REPORTING) 105 .runWithLock( 106 "EventFallbackReportingJobService", 107 () -> { 108 long maxEventReportUploadRetryWindowMs = 109 FlagsFactory.getFlags() 110 .getMeasurementMaxEventReportUploadRetryWindowMs(); 111 long eventMainReportingJobPeriodMs = 112 AdServicesConfig.getMeasurementEventMainReportingJobPeriodMs(); 113 new EventReportingJobHandler( 114 DatastoreManagerFactory.getDatastoreManager(), 115 FlagsFactory.getFlags(), 116 AdServicesLoggerImpl.getInstance(), 117 ReportingStatus.ReportType.EVENT, 118 ReportingStatus.UploadMethod.FALLBACK, 119 getApplicationContext(), 120 new AndroidTimeSource()) 121 .performScheduledPendingReportsInWindow( 122 System.currentTimeMillis() 123 - maxEventReportUploadRetryWindowMs, 124 System.currentTimeMillis() 125 - eventMainReportingJobPeriodMs); 126 }); 127 } 128 129 @Override onStopJob(JobParameters params)130 public boolean onStopJob(JobParameters params) { 131 LoggerFactory.getMeasurementLogger().d("EventFallbackReportingJobService.onStopJob"); 132 boolean shouldRetry = true; 133 if (mExecutorFuture != null) { 134 shouldRetry = mExecutorFuture.cancel(/* mayInterruptIfRunning */ true); 135 } 136 AdServicesJobServiceLogger.getInstance() 137 .recordOnStopJob(params, MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID, shouldRetry); 138 return shouldRetry; 139 } 140 141 /** Schedules {@link EventFallbackReportingJobService} */ 142 @VisibleForTesting schedule(JobScheduler jobScheduler, JobInfo jobInfo)143 static void schedule(JobScheduler jobScheduler, JobInfo jobInfo) { 144 jobScheduler.schedule(jobInfo); 145 } 146 147 /** 148 * Schedule Event Fallback Reporting Job if it is not already scheduled 149 * 150 * @param context the context 151 * @param forceSchedule flag to indicate whether to force rescheduling the job. 152 */ 153 // TODO(b/311183933): Remove passed in Context from static method. 154 @SuppressWarnings("AvoidStaticContext") scheduleIfNeeded(Context context, boolean forceSchedule)155 public static void scheduleIfNeeded(Context context, boolean forceSchedule) { 156 Flags flags = FlagsFactory.getFlags(); 157 if (flags.getMeasurementJobEventFallbackReportingKillSwitch()) { 158 LoggerFactory.getMeasurementLogger() 159 .d("EventFallbackReportingJobService is disabled, skip scheduling"); 160 return; 161 } 162 163 final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class); 164 if (jobScheduler == null) { 165 LoggerFactory.getMeasurementLogger().e("JobScheduler not found"); 166 return; 167 } 168 169 final JobInfo scheduledJob = 170 jobScheduler.getPendingJob(MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID); 171 // Schedule if it hasn't been scheduled already or force rescheduling 172 JobInfo jobInfo = buildJobInfo(context, flags); 173 if (forceSchedule || !jobInfo.equals(scheduledJob)) { 174 schedule(jobScheduler, jobInfo); 175 LoggerFactory.getMeasurementLogger().d("Scheduled EventFallbackReportingJobService"); 176 } else { 177 LoggerFactory.getMeasurementLogger() 178 .d("EventFallbackReportingJobService already scheduled, skipping reschedule"); 179 } 180 } 181 182 // TODO(b/311183933): Remove passed in Context from static method. 183 @SuppressWarnings("AvoidStaticContext") buildJobInfo(Context context, Flags flags)184 private static JobInfo buildJobInfo(Context context, Flags flags) { 185 return new JobInfo.Builder( 186 MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID, 187 new ComponentName(context, EventFallbackReportingJobService.class)) 188 .setRequiresBatteryNotLow( 189 flags.getMeasurementEventFallbackReportingJobRequiredBatteryNotLow()) 190 .setRequiredNetworkType( 191 flags.getMeasurementEventFallbackReportingJobRequiredNetworkType()) 192 .setPeriodic(flags.getMeasurementEventFallbackReportingJobPeriodMs()) 193 .setPersisted(flags.getMeasurementEventFallbackReportingJobPersisted()) 194 .build(); 195 } 196 skipAndCancelBackgroundJob( final JobParameters params, int skipReason, boolean doRecord)197 private boolean skipAndCancelBackgroundJob( 198 final JobParameters params, int skipReason, boolean doRecord) { 199 final JobScheduler jobScheduler = this.getSystemService(JobScheduler.class); 200 if (jobScheduler != null) { 201 jobScheduler.cancel(MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID); 202 } 203 204 if (doRecord) { 205 AdServicesJobServiceLogger.getInstance() 206 .recordJobSkipped(MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID, skipReason); 207 } 208 209 // Tell the JobScheduler that the job has completed and does not need to be rescheduled. 210 jobFinished(params, false); 211 212 // Returning false means that this job has completed its work. 213 return false; 214 } 215 216 @VisibleForTesting getFutureForTesting()217 Future getFutureForTesting() { 218 return mExecutorFuture; 219 } 220 } 221