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.common.util.concurrent.ListeningExecutorService;
44 
45 import java.util.concurrent.Future;
46 
47 /**
48  * Fallback service for scheduling reporting jobs (runs less frequently than the main service
49  * without a network type requirement). The actual job execution logic is part of {@link
50  * EventReportingJobHandler}
51  */
52 public final class EventFallbackReportingJobService extends JobService {
53     private static final int MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID =
54             MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB.getJobId();
55 
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                     "Disabling EventFallbackReportingJobService job because it's running in"
68                             + " ExtServices on T+");
69             return skipAndCancelBackgroundJob(params, /* skipReason=*/ 0, /* doRecord=*/ false);
70         }
71 
72         AdServicesJobServiceLogger.getInstance()
73                 .recordOnStartJob(MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID);
74 
75         if (FlagsFactory.getFlags().getMeasurementJobEventFallbackReportingKillSwitch()) {
76             LoggerFactory.getMeasurementLogger()
77                     .e("EventFallbackReportingJobService Job is disabled");
78             return skipAndCancelBackgroundJob(
79                     params,
80                     AD_SERVICES_BACKGROUND_JOBS_EXECUTION_REPORTED__EXECUTION_RESULT_CODE__SKIP_FOR_KILL_SWITCH_ON,
81                     /* doRecord=*/ true);
82         }
83 
84         LoggerFactory.getMeasurementLogger().d("EventFallbackReportingJobService.onStartJob");
85         mExecutorFuture =
86                 sBlockingExecutor.submit(
87                         () -> {
88                             processPendingReports();
89 
90                             AdServicesJobServiceLogger.getInstance()
91                                     .recordJobFinished(
92                                             MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID,
93                                             /* isSuccessful= */ true,
94                                             /* shouldRetry= */ false);
95 
96                             jobFinished(params, /* wantsReschedule= */ false);
97                         });
98         return true;
99     }
100 
101     @VisibleForTesting
processPendingReports()102     void processPendingReports() {
103         final JobLockHolder lock = JobLockHolder.getInstance(EVENT_REPORTING);
104         if (lock.tryLock()) {
105             try {
106                 long maxEventReportUploadRetryWindowMs =
107                         FlagsFactory.getFlags().getMeasurementMaxEventReportUploadRetryWindowMs();
108                 long eventMainReportingJobPeriodMs =
109                         AdServicesConfig.getMeasurementEventMainReportingJobPeriodMs();
110                 new EventReportingJobHandler(
111                                 DatastoreManagerFactory.getDatastoreManager(
112                                         getApplicationContext()),
113                                 FlagsFactory.getFlags(),
114                                 AdServicesLoggerImpl.getInstance(),
115                                 ReportingStatus.ReportType.EVENT,
116                                 ReportingStatus.UploadMethod.FALLBACK,
117                                 getApplicationContext())
118                         .performScheduledPendingReportsInWindow(
119                                 System.currentTimeMillis() - maxEventReportUploadRetryWindowMs,
120                                 System.currentTimeMillis() - eventMainReportingJobPeriodMs);
121                 return;
122             } finally {
123                 lock.unlock();
124             }
125         }
126         LoggerFactory.getMeasurementLogger()
127                 .d("EventFallbackReportingJobService did not acquire the lock");
128     }
129 
130     @Override
onStopJob(JobParameters params)131     public boolean onStopJob(JobParameters params) {
132         LoggerFactory.getMeasurementLogger().d("EventFallbackReportingJobService.onStopJob");
133         boolean shouldRetry = true;
134         if (mExecutorFuture != null) {
135             shouldRetry = mExecutorFuture.cancel(/* mayInterruptIfRunning */ true);
136         }
137         AdServicesJobServiceLogger.getInstance()
138                 .recordOnStopJob(params, MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID, shouldRetry);
139         return shouldRetry;
140     }
141 
142     /** Schedules {@link EventFallbackReportingJobService} */
143     @VisibleForTesting
schedule(JobScheduler jobScheduler, JobInfo jobInfo)144     static void schedule(JobScheduler jobScheduler, JobInfo jobInfo) {
145         jobScheduler.schedule(jobInfo);
146     }
147 
148     /**
149      * Schedule Event Fallback Reporting Job if it is not already scheduled
150      *
151      * @param context the context
152      * @param forceSchedule flag to indicate whether to force rescheduling the job.
153      */
scheduleIfNeeded(Context context, boolean forceSchedule)154     public static void scheduleIfNeeded(Context context, boolean forceSchedule) {
155         Flags flags = FlagsFactory.getFlags();
156         if (flags.getMeasurementJobEventFallbackReportingKillSwitch()) {
157             LoggerFactory.getMeasurementLogger()
158                     .d("EventFallbackReportingJobService is disabled, skip scheduling");
159             return;
160         }
161 
162         final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
163         if (jobScheduler == null) {
164             LoggerFactory.getMeasurementLogger().e("JobScheduler not found");
165             return;
166         }
167 
168         final JobInfo scheduledJob =
169                 jobScheduler.getPendingJob(MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID);
170         // Schedule if it hasn't been scheduled already or force rescheduling
171         JobInfo jobInfo = buildJobInfo(context, flags);
172         if (forceSchedule || !jobInfo.equals(scheduledJob)) {
173             schedule(jobScheduler, jobInfo);
174             LoggerFactory.getMeasurementLogger().d("Scheduled EventFallbackReportingJobService");
175         } else {
176             LoggerFactory.getMeasurementLogger()
177                     .d("EventFallbackReportingJobService already scheduled, skipping reschedule");
178         }
179     }
180 
buildJobInfo(Context context, Flags flags)181     private static JobInfo buildJobInfo(Context context, Flags flags) {
182         return new JobInfo.Builder(
183                         MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID,
184                         new ComponentName(context, EventFallbackReportingJobService.class))
185                 .setRequiresBatteryNotLow(
186                         flags.getMeasurementEventFallbackReportingJobRequiredBatteryNotLow())
187                 .setRequiredNetworkType(
188                         flags.getMeasurementEventFallbackReportingJobRequiredNetworkType())
189                 .setPeriodic(flags.getMeasurementEventFallbackReportingJobPeriodMs())
190                 .setPersisted(flags.getMeasurementEventFallbackReportingJobPersisted())
191                 .build();
192     }
193 
skipAndCancelBackgroundJob( final JobParameters params, int skipReason, boolean doRecord)194     private boolean skipAndCancelBackgroundJob(
195             final JobParameters params, int skipReason, boolean doRecord) {
196         final JobScheduler jobScheduler = this.getSystemService(JobScheduler.class);
197         if (jobScheduler != null) {
198             jobScheduler.cancel(MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID);
199         }
200 
201         if (doRecord) {
202             AdServicesJobServiceLogger.getInstance()
203                     .recordJobSkipped(MEASUREMENT_EVENT_FALLBACK_REPORTING_JOB_ID, skipReason);
204         }
205 
206         // Tell the JobScheduler that the job has completed and does not need to be rescheduled.
207         jobFinished(params, false);
208 
209         // Returning false means that this job has completed its work.
210         return false;
211     }
212 
213     @VisibleForTesting
getFutureForTesting()214     Future getFutureForTesting() {
215         return mExecutorFuture;
216     }
217 }
218