• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.VERBOSE_DEBUG_REPORTING;
20 import static com.android.adservices.spe.AdServicesJobInfo.MEASUREMENT_VERBOSE_DEBUG_REPORT_JOB;
21 
22 import android.app.job.JobInfo;
23 import android.app.job.JobParameters;
24 import android.app.job.JobScheduler;
25 import android.app.job.JobService;
26 import android.content.ComponentName;
27 import android.content.Context;
28 
29 import com.android.adservices.LogUtil;
30 import com.android.adservices.LoggerFactory;
31 import com.android.adservices.concurrency.AdServicesExecutors;
32 import com.android.adservices.data.measurement.DatastoreManager;
33 import com.android.adservices.data.measurement.DatastoreManagerFactory;
34 import com.android.adservices.service.Flags;
35 import com.android.adservices.service.FlagsFactory;
36 import com.android.adservices.service.common.compat.ServiceCompatUtils;
37 import com.android.adservices.service.measurement.util.JobLockHolder;
38 import com.android.adservices.service.stats.AdServicesLoggerImpl;
39 import com.android.adservices.spe.AdServicesJobServiceLogger;
40 import com.android.internal.annotations.VisibleForTesting;
41 
42 import com.google.common.util.concurrent.ListeningExecutorService;
43 
44 import java.util.concurrent.Future;
45 
46 /**
47  * Main service for scheduling verbose debug reporting jobs. The actual job execution logic is part
48  * of {@link DebugReportingJobHandler }.
49  */
50 public final class VerboseDebugReportingJobService extends JobService {
51     private static final ListeningExecutorService sBlockingExecutor =
52             AdServicesExecutors.getBlockingExecutor();
53     static final int VERBOSE_DEBUG_REPORT_JOB_ID = MEASUREMENT_VERBOSE_DEBUG_REPORT_JOB.getJobId();
54 
55     private Future mExecutorFuture;
56 
57     @Override
onStartJob(JobParameters params)58     public boolean onStartJob(JobParameters params) {
59         // Always ensure that the first thing this job does is check if it should be running, and
60         // cancel itself if it's not supposed to be.
61         if (ServiceCompatUtils.shouldDisableExtServicesJobOnTPlus(this)) {
62             LogUtil.d(
63                     "Disabling VerboseDebugReportingJobService job because it's running in "
64                             + "ExtServices on T+");
65             return skipAndCancelBackgroundJob(params);
66         }
67 
68         AdServicesJobServiceLogger.getInstance().recordOnStartJob(VERBOSE_DEBUG_REPORT_JOB_ID);
69 
70         if (FlagsFactory.getFlags().getMeasurementJobVerboseDebugReportingKillSwitch()) {
71             LoggerFactory.getMeasurementLogger().e("VerboseDebugReportingJobService is disabled");
72             return skipAndCancelBackgroundJob(params);
73         }
74 
75         LoggerFactory.getMeasurementLogger().d("VerboseDebugReportingJobService.onStartJob");
76         mExecutorFuture =
77                 sBlockingExecutor.submit(
78                         () -> {
79                             sendReports();
80                             AdServicesJobServiceLogger.getInstance()
81                                     .recordJobFinished(
82                                             VERBOSE_DEBUG_REPORT_JOB_ID,
83                                             /* isSuccessful */ true,
84                                             /* shouldRetry*/ false);
85                             jobFinished(params, /* wantsReschedule= */ false);
86                         });
87         return true;
88     }
89 
90     @Override
onStopJob(JobParameters params)91     public boolean onStopJob(JobParameters params) {
92         LoggerFactory.getMeasurementLogger().d("VerboseDebugReportingJobService.onStopJob");
93         boolean shouldRetry = true;
94         if (mExecutorFuture != null) {
95             shouldRetry = mExecutorFuture.cancel(/* mayInterruptIfRunning */ true);
96         }
97         AdServicesJobServiceLogger.getInstance()
98                 .recordOnStopJob(params, VERBOSE_DEBUG_REPORT_JOB_ID, shouldRetry);
99         return shouldRetry;
100     }
101 
102     /** Schedules {@link VerboseDebugReportingJobService} */
103     @VisibleForTesting
schedule(JobScheduler jobScheduler, JobInfo jobInfo)104     static void schedule(JobScheduler jobScheduler, JobInfo jobInfo) {
105         jobScheduler.schedule(jobInfo);
106     }
107 
108     /**
109      * Schedule Verbose Debug Reporting Job if it is not already scheduled
110      *
111      * @param context the context
112      * @param forceSchedule flag to indicate whether to force rescheduling the job.
113      */
114     // TODO(b/311183933): Remove passed in Context from static method.
115     @SuppressWarnings("AvoidStaticContext")
scheduleIfNeeded(Context context, boolean forceSchedule)116     public static void scheduleIfNeeded(Context context, boolean forceSchedule) {
117         Flags flags = FlagsFactory.getFlags();
118         if (flags.getMeasurementJobVerboseDebugReportingKillSwitch()) {
119             LoggerFactory.getMeasurementLogger()
120                     .d("VerboseDebugReportingJobService is disabled, skip scheduling");
121             return;
122         }
123 
124         final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
125         if (jobScheduler == null) {
126             LoggerFactory.getMeasurementLogger().e("JobScheduler not found");
127             return;
128         }
129 
130         final JobInfo scheduledJob = jobScheduler.getPendingJob(VERBOSE_DEBUG_REPORT_JOB_ID);
131         // Schedule if it hasn't been scheduled already or force rescheduling
132         JobInfo jobInfo = buildJobInfo(context, flags);
133         if (forceSchedule || !jobInfo.equals(scheduledJob)) {
134             schedule(jobScheduler, jobInfo);
135             LoggerFactory.getMeasurementLogger().d("Scheduled VerboseDebugReportingJobService");
136         } else {
137             LoggerFactory.getMeasurementLogger()
138                     .d("VerboseDebugReportingJobService already scheduled, skipping reschedule");
139         }
140     }
141 
142     // TODO(b/311183933): Remove passed in Context from static method.
143     @SuppressWarnings("AvoidStaticContext")
buildJobInfo(Context context, Flags flags)144     private static JobInfo buildJobInfo(Context context, Flags flags) {
145         return new JobInfo.Builder(
146                         VERBOSE_DEBUG_REPORT_JOB_ID,
147                         new ComponentName(context, VerboseDebugReportingJobService.class))
148                 .setRequiredNetworkType(
149                         flags.getMeasurementVerboseDebugReportingJobRequiredNetworkType())
150                 .build();
151     }
152 
skipAndCancelBackgroundJob(final JobParameters params)153     private boolean skipAndCancelBackgroundJob(final JobParameters params) {
154         final JobScheduler jobScheduler = this.getSystemService(JobScheduler.class);
155         if (jobScheduler != null) {
156             jobScheduler.cancel(VERBOSE_DEBUG_REPORT_JOB_ID);
157         }
158 
159         // Tell the JobScheduler that the job has completed and does not need to be rescheduled.
160         jobFinished(params, /* wantsReschedule= */ false);
161 
162         // Returning false means that this job has completed its work.
163         return false;
164     }
165 
166     @VisibleForTesting
sendReports()167     void sendReports() {
168         JobLockHolder.getInstance(VERBOSE_DEBUG_REPORTING)
169                 .runWithLock(
170                         "VerboseDebugReportingJobService",
171                         () -> {
172                             DatastoreManager datastoreManager =
173                                     DatastoreManagerFactory.getDatastoreManager();
174                             new DebugReportingJobHandler(
175                                             datastoreManager,
176                                             FlagsFactory.getFlags(),
177                                             AdServicesLoggerImpl.getInstance(),
178                                             ReportingStatus.UploadMethod.REGULAR,
179                                             getApplicationContext())
180                                     .performScheduledPendingReports();
181                         });
182         }
183 
184     @VisibleForTesting
getFutureForTesting()185     Future getFutureForTesting() {
186         return mExecutorFuture;
187     }
188 }
189