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;
18 
19 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_BACKGROUND_JOBS_EXECUTION_REPORTED__EXECUTION_RESULT_CODE__SKIP_FOR_KILL_SWITCH_ON;
20 import static com.android.adservices.spe.AdServicesJobInfo.MEASUREMENT_DELETE_UNINSTALLED_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 import android.os.Build;
29 
30 import androidx.annotation.RequiresApi;
31 
32 import com.android.adservices.LogUtil;
33 import com.android.adservices.LoggerFactory;
34 import com.android.adservices.concurrency.AdServicesExecutors;
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.spe.AdServicesJobServiceLogger;
39 import com.android.internal.annotations.VisibleForTesting;
40 
41 import java.util.concurrent.Executor;
42 
43 /**
44  * Service for deleting data for uninstalled packages that the package change receiver has missed.
45  */
46 // TODO(b/269798827): Enable for R.
47 @RequiresApi(Build.VERSION_CODES.S)
48 public final class DeleteUninstalledJobService extends JobService {
49     private static final int MEASUREMENT_DELETE_UNINSTALLED_JOB_ID =
50             MEASUREMENT_DELETE_UNINSTALLED_JOB.getJobId();
51     private static final Executor sBackgroundExecutor = AdServicesExecutors.getBackgroundExecutor();
52 
53     @Override
onStartJob(JobParameters params)54     public boolean onStartJob(JobParameters params) {
55         // Always ensure that the first thing this job does is check if it should be running, and
56         // cancel itself if it's not supposed to be.
57         if (ServiceCompatUtils.shouldDisableExtServicesJobOnTPlus(this)) {
58             LogUtil.d(
59                     "Disabling DeleteUninstalledJobService job because it's running in ExtServices"
60                             + " on T+");
61             return skipAndCancelBackgroundJob(params, /* skipReason=*/ 0, /* doRecord=*/ false);
62         }
63 
64         AdServicesJobServiceLogger.getInstance()
65                 .recordOnStartJob(MEASUREMENT_DELETE_UNINSTALLED_JOB_ID);
66 
67         if (FlagsFactory.getFlags().getMeasurementJobDeleteUninstalledKillSwitch()) {
68             LoggerFactory.getMeasurementLogger().e("DeleteUninstalledJobService is disabled");
69             return skipAndCancelBackgroundJob(
70                     params,
71                     AD_SERVICES_BACKGROUND_JOBS_EXECUTION_REPORTED__EXECUTION_RESULT_CODE__SKIP_FOR_KILL_SWITCH_ON,
72                     /* doRecord=*/ true);
73         }
74 
75         LoggerFactory.getMeasurementLogger().d("DeleteUninstalledJobService.onStartJob");
76         sBackgroundExecutor.execute(
77                 () -> {
78                     MeasurementImpl.getInstance(this).deleteAllUninstalledMeasurementData();
79 
80                     boolean shouldRetry = false;
81                     AdServicesJobServiceLogger.getInstance()
82                             .recordJobFinished(
83                                     MEASUREMENT_DELETE_UNINSTALLED_JOB_ID,
84                                     /* isSuccessful */ true,
85                                     shouldRetry);
86                     jobFinished(params, shouldRetry);
87                 });
88         return true;
89     }
90 
91     @Override
onStopJob(JobParameters params)92     public boolean onStopJob(JobParameters params) {
93         LoggerFactory.getMeasurementLogger().d("DeleteUninstalledJobService.onStopJob");
94         boolean shouldRetry = false;
95 
96         AdServicesJobServiceLogger.getInstance()
97                 .recordOnStopJob(params, MEASUREMENT_DELETE_UNINSTALLED_JOB_ID, shouldRetry);
98         return shouldRetry;
99     }
100 
101     /** Schedule the job. */
102     @VisibleForTesting
schedule(JobScheduler jobScheduler, JobInfo jobInfo)103     static void schedule(JobScheduler jobScheduler, JobInfo jobInfo) {
104         jobScheduler.schedule(jobInfo);
105     }
106 
107     /**
108      * Schedule Delete Uninstalled Job Service if it is not already scheduled.
109      *
110      * @param context the context
111      * @param forceSchedule flag to indicate whether to force rescheduling the job.
112      */
scheduleIfNeeded(Context context, boolean forceSchedule)113     public static void scheduleIfNeeded(Context context, boolean forceSchedule) {
114         Flags flags = FlagsFactory.getFlags();
115         if (flags.getMeasurementJobDeleteUninstalledKillSwitch()) {
116             LoggerFactory.getMeasurementLogger()
117                     .e("DeleteUninstalledJobService is disabled, skip scheduling");
118             return;
119         }
120 
121         final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
122         if (jobScheduler == null) {
123             LoggerFactory.getMeasurementLogger().e("JobScheduler not found");
124             return;
125         }
126 
127         final JobInfo scheduledJob =
128                 jobScheduler.getPendingJob(MEASUREMENT_DELETE_UNINSTALLED_JOB_ID);
129         // Schedule if it hasn't been scheduled already or force rescheduling.
130         JobInfo jobInfo = buildJobInfo(context, flags);
131         if (forceSchedule || !jobInfo.equals(scheduledJob)) {
132             schedule(jobScheduler, jobInfo);
133             LoggerFactory.getMeasurementLogger().d("Scheduled DeleteUninstalledJobService");
134         } else {
135             LoggerFactory.getMeasurementLogger()
136                     .d("DeleteUninstalledJobService already scheduled, skipping reschedule");
137         }
138     }
139 
buildJobInfo(Context context, Flags flags)140     private static JobInfo buildJobInfo(Context context, Flags flags) {
141         return new JobInfo.Builder(
142                         MEASUREMENT_DELETE_UNINSTALLED_JOB_ID,
143                         new ComponentName(context, DeleteUninstalledJobService.class))
144                 .setPeriodic(flags.getMeasurementDeleteUninstalledJobPeriodMs())
145                 .setPersisted(flags.getMeasurementDeleteUninstalledJobPersisted())
146                 .build();
147     }
148 
skipAndCancelBackgroundJob( final JobParameters params, int skipReason, boolean doRecord)149     private boolean skipAndCancelBackgroundJob(
150             final JobParameters params, int skipReason, boolean doRecord) {
151         final JobScheduler jobScheduler = this.getSystemService(JobScheduler.class);
152         if (jobScheduler != null) {
153             jobScheduler.cancel(MEASUREMENT_DELETE_UNINSTALLED_JOB_ID);
154         }
155 
156         if (doRecord) {
157             AdServicesJobServiceLogger.getInstance()
158                     .recordJobSkipped(MEASUREMENT_DELETE_UNINSTALLED_JOB_ID, skipReason);
159         }
160 
161         // Tell the JobScheduler that the job has completed and does not need to be rescheduled.
162         jobFinished(params, /* wantsReschedule */ false);
163 
164         // Returning false meas that this job has completed its work.
165         return false;
166     }
167 }
168