1 /*
2  * Copyright (C) 2024 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.AGGREGATE_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_IMMEDIATE_AGGREGATE_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.DatastoreManager;
34 import com.android.adservices.data.measurement.DatastoreManagerFactory;
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.aggregation.AggregateEncryptionKeyManager;
39 import com.android.adservices.service.measurement.util.JobLockHolder;
40 import com.android.adservices.service.stats.AdServicesLoggerImpl;
41 import com.android.adservices.spe.AdServicesJobServiceLogger;
42 import com.android.internal.annotations.VisibleForTesting;
43 
44 import com.google.common.util.concurrent.ListeningExecutorService;
45 
46 import java.util.concurrent.Future;
47 
48 /**
49  * Service for immediately scheduling aggregate reporting jobs. Aggregate reports that have trigger
50  * context ids are meant for immediate delivery. The actual job execution logic is part of {@link
51  * AggregateReportingJobHandler}
52  */
53 public final class ImmediateAggregateReportingJobService extends JobService {
54     private static final int MEASUREMENT_IMMEDIATE_AGGREGATE_REPORTING_JOB_ID =
55             MEASUREMENT_IMMEDIATE_AGGREGATE_REPORTING_JOB.getJobId();
56     private static final ListeningExecutorService sBlockingExecutor =
57             AdServicesExecutors.getBlockingExecutor();
58 
59     private Future mExecutorFuture;
60 
61     @Override
onStartJob(JobParameters params)62     public boolean onStartJob(JobParameters params) {
63         // Always ensure that the first thing this job does is check if it should be running, and
64         // cancel itself if it's not supposed to be.
65         if (ServiceCompatUtils.shouldDisableExtServicesJobOnTPlus(this)) {
66             LogUtil.d(
67                     String.format(
68                             "Disabling %s job because it's running in" + " ExtServices on T+",
69                             this.getClass().getSimpleName()));
70             return skipAndCancelBackgroundJob(params, /* skipReason=*/ 0, /* doRecord=*/ false);
71         }
72 
73         AdServicesJobServiceLogger.getInstance()
74                 .recordOnStartJob(MEASUREMENT_IMMEDIATE_AGGREGATE_REPORTING_JOB_ID);
75 
76         if (FlagsFactory.getFlags().getMeasurementJobImmediateAggregateReportingKillSwitch()) {
77             LoggerFactory.getMeasurementLogger()
78                     .e(this.getClass().getSimpleName() + " 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(this.getClass().getSimpleName() + ".onStartJob");
86         mExecutorFuture =
87                 sBlockingExecutor.submit(
88                         () -> {
89                             processPendingReports();
90 
91                             AdServicesJobServiceLogger.getInstance()
92                                     .recordJobFinished(
93                                             MEASUREMENT_IMMEDIATE_AGGREGATE_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         final JobLockHolder lock = JobLockHolder.getInstance(AGGREGATE_REPORTING);
105         if (lock.tryLock()) {
106             try {
107                 long maxAggregateReportUploadRetryWindowMs =
108                         FlagsFactory.getFlags()
109                                 .getMeasurementMaxAggregateReportUploadRetryWindowMs();
110                 DatastoreManager datastoreManager =
111                         DatastoreManagerFactory.getDatastoreManager(getApplicationContext());
112                 new AggregateReportingJobHandler(
113                                 datastoreManager,
114                                 new AggregateEncryptionKeyManager(
115                                         datastoreManager, getApplicationContext()),
116                                 FlagsFactory.getFlags(),
117                                 AdServicesLoggerImpl.getInstance(),
118                                 ReportingStatus.ReportType.AGGREGATE,
119                                 ReportingStatus.UploadMethod.REGULAR,
120                                 getApplicationContext())
121                         .performScheduledPendingReportsInWindow(
122                                 System.currentTimeMillis() - maxAggregateReportUploadRetryWindowMs,
123                                 System.currentTimeMillis());
124                 return;
125             } finally {
126                 lock.unlock();
127             }
128         }
129         LoggerFactory.getMeasurementLogger()
130                 .d(this.getClass().getSimpleName() + " did not acquire the lock");
131     }
132 
133     @Override
onStopJob(JobParameters params)134     public boolean onStopJob(JobParameters params) {
135         LoggerFactory.getMeasurementLogger().d(this.getClass().getSimpleName() + ".onStopJob");
136         boolean shouldRetry = true;
137         if (mExecutorFuture != null) {
138             shouldRetry = mExecutorFuture.cancel(/* mayInterruptIfRunning */ true);
139         }
140         AdServicesJobServiceLogger.getInstance()
141                 .recordOnStopJob(
142                         params, MEASUREMENT_IMMEDIATE_AGGREGATE_REPORTING_JOB_ID, shouldRetry);
143         return shouldRetry;
144     }
145 
146     /** Schedules {@link ImmediateAggregateReportingJobService} */
147     @VisibleForTesting
schedule(JobScheduler jobScheduler, JobInfo job)148     static void schedule(JobScheduler jobScheduler, JobInfo job) {
149         jobScheduler.schedule(job);
150     }
151 
152     /**
153      * Schedule Immediate Aggregate Reporting Job if it is not already scheduled
154      *
155      * @param context the context
156      * @param forceSchedule flag to indicate whether to force rescheduling the job.
157      */
scheduleIfNeeded(Context context, boolean forceSchedule)158     public static void scheduleIfNeeded(Context context, boolean forceSchedule) {
159         Flags flags = FlagsFactory.getFlags();
160         if (flags.getMeasurementJobImmediateAggregateReportingKillSwitch()) {
161             LoggerFactory.getMeasurementLogger()
162                     .d("ImmediateAggregateReportingJobService is disabled, skip scheduling");
163             return;
164         }
165 
166         final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
167         if (jobScheduler == null) {
168             LoggerFactory.getMeasurementLogger().e("JobScheduler not found");
169             return;
170         }
171 
172         final JobInfo scheduledJobInfo =
173                 jobScheduler.getPendingJob(MEASUREMENT_IMMEDIATE_AGGREGATE_REPORTING_JOB_ID);
174         JobInfo jobInfo = buildJobInfo(context, flags);
175         // Schedule if it hasn't been scheduled already or force rescheduling
176         if (forceSchedule || !jobInfo.equals(scheduledJobInfo)) {
177             schedule(jobScheduler, jobInfo);
178             LoggerFactory.getMeasurementLogger()
179                     .d("Scheduled ImmediateAggregateReportingJobService");
180         } else {
181             LoggerFactory.getMeasurementLogger()
182                     .d(
183                             "ImmediateAggregateReportingJobService already scheduled, skipping"
184                                     + " reschedule");
185         }
186     }
187 
buildJobInfo(Context context, Flags flags)188     private static JobInfo buildJobInfo(Context context, Flags flags) {
189         return new JobInfo.Builder(
190                         MEASUREMENT_IMMEDIATE_AGGREGATE_REPORTING_JOB_ID,
191                         new ComponentName(context, ImmediateAggregateReportingJobService.class))
192                 .setRequiresBatteryNotLow(
193                         flags.getMeasurementImmediateAggregateReportingJobRequiredBatteryNotLow())
194                 .setRequiredNetworkType(
195                         flags.getMeasurementImmediateAggregateReportingJobRequiredNetworkType())
196                 .setPersisted(flags.getMeasurementImmediateAggregateReportingJobPersisted())
197                 .build();
198     }
199 
skipAndCancelBackgroundJob( final JobParameters params, int skipReason, boolean doRecord)200     private boolean skipAndCancelBackgroundJob(
201             final JobParameters params, int skipReason, boolean doRecord) {
202         final JobScheduler jobScheduler = this.getSystemService(JobScheduler.class);
203         if (jobScheduler != null) {
204             jobScheduler.cancel(MEASUREMENT_IMMEDIATE_AGGREGATE_REPORTING_JOB_ID);
205         }
206 
207         if (doRecord) {
208             AdServicesJobServiceLogger.getInstance()
209                     .recordJobSkipped(MEASUREMENT_IMMEDIATE_AGGREGATE_REPORTING_JOB_ID, skipReason);
210         }
211 
212         // Tell the JobScheduler that the job has completed and does not need to be rescheduled.
213         jobFinished(params, false);
214 
215         // Returning false means that this job has completed its work.
216         return false;
217     }
218 
219     @VisibleForTesting
getFutureForTesting()220     Future getFutureForTesting() {
221         return mExecutorFuture;
222     }
223 }
224