Debian Codegraph @

apex/jobscheduler/service/java/com/android/server/job/controllers/ComponentController.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2020 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.server.job.controllers;
18
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.content.BroadcastReceiver;
22 import android.content.ComponentName;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.IntentFilter;
26 import android.content.pm.PackageManager;
27 import android.content.pm.PackageManager.NameNotFoundException;
28 import android.content.pm.ServiceInfo;
29 import android.net.Uri;
30 import android.os.UserHandle;
31 import android.util.ArraySet;
32 import android.util.IndentingPrintWriter;
33 import android.util.Log;
34 import android.util.Slog;
35 import android.util.SparseArrayMap;
36 import android.util.proto.ProtoOutputStream;
37
38 import com.android.internal.annotations.GuardedBy;
39 import com.android.server.job.JobSchedulerService;
40
41 import java.util.Objects;
42 import java.util.function.Consumer;
43 import java.util.function.Predicate;
44
45 /**
46 * Controller that tracks changes in the service component's enabled state.
47 */
48 public class ComponentController extends StateController {
49 private static final String TAG = "JobScheduler.Component";
50 private static final boolean DEBUG = JobSchedulerService.DEBUG
51 || Log.isLoggable(TAG, Log.DEBUG);
52
53 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
54
55 @Override
56 public void onReceive(Context context, Intent intent) {
57 final String action = intent.getAction();
58 if (action == null) {
59 Slog.wtf(TAG, "Intent action was null");
60 return;
61 }
62 switch (action) {
63 case Intent.ACTION_PACKAGE_ADDED:
64 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
65 // Only do this for app updates since new installs won't have any jobs
66 // scheduled.
67 final Uri uri = intent.getData();
68 final String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
69 if (pkg != null) {
70 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
71 final int userId = UserHandle.getUserId(pkgUid);
72 updateComponentStateForPackage(userId, pkg);
73 }
74 }
75 break;
76 case Intent.ACTION_PACKAGE_CHANGED:
77 final Uri uri = intent.getData();
78 final String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
79 final String[] changedComponents = intent.getStringArrayExtra(
80 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
81 if (pkg != null && changedComponents != null && changedComponents.length > 0) {
82 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
83 final int userId = UserHandle.getUserId(pkgUid);
84 updateComponentStateForPackage(userId, pkg);
85 }
86 break;
87 case Intent.ACTION_USER_UNLOCKED:
88 case Intent.ACTION_USER_STOPPED:
89 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
90 updateComponentStateForUser(userId);
91 break;
92 }
93 }
94 };
95
96 private final SparseArrayMap<ComponentName, ServiceInfo> mServiceInfoCache =
97 new SparseArrayMap<>();
98
99 private final ComponentStateUpdateFunctor mComponentStateUpdateFunctor =
100 new ComponentStateUpdateFunctor();
101
102 public ComponentController(JobSchedulerService service) {
103 super(service);
104
105 final IntentFilter filter = new IntentFilter();
106 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
107 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
108 filter.addDataScheme("package");
109 mContext.registerReceiverAsUser(
110 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
111 final IntentFilter userFilter = new IntentFilter();
112 userFilter.addAction(Intent.ACTION_USER_UNLOCKED);
113 userFilter.addAction(Intent.ACTION_USER_STOPPED);
114 mContext.registerReceiverAsUser(
115 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
116 }
117
118 @Override
119 @GuardedBy("mLock")
120 public void maybeStartTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
121 updateComponentEnabledStateLocked(jobStatus);
122 }
123
124 @Override
125 public void maybeStopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
126 boolean forUpdate) {
127 }
128
129 @Override
130 @GuardedBy("mLock")
131 public void onAppRemovedLocked(String packageName, int uid) {
132 clearComponentsForPackageLocked(UserHandle.getUserId(uid), packageName);
133 }
134
135 @Override
136 @GuardedBy("mLock")
137 public void onUserRemovedLocked(int userId) {
138 mServiceInfoCache.delete(userId);
139 }
140
141 @Nullable
142 @GuardedBy("mLock")
143 private ServiceInfo getServiceInfoLocked(JobStatus jobStatus) {
144 final ComponentName service = jobStatus.getServiceComponent();
145 final int userId = jobStatus.getUserId();
146 if (mServiceInfoCache.contains(userId, service)) {
147 // Return whatever is in the cache, even if it's null. When something changes, we
148 // clear the cache.
149 return mServiceInfoCache.get(userId, service);
150 }
151
152 ServiceInfo si;
153 try {
154 // createContextAsUser may potentially be expensive
155 // TODO: cache user context or improve ContextImpl implementation if this becomes
156 // a problem
157 si = mContext.createContextAsUser(UserHandle.of(userId), 0)
158 .getPackageManager()
159 .getServiceInfo(service, PackageManager.MATCH_DIRECT_BOOT_AUTO);
160 } catch (NameNotFoundException e) {
161 if (mService.areUsersStartedLocked(jobStatus)) {
162 // User is fully unlocked but PM still says the package doesn't exist.
163 Slog.e(TAG, "Job exists for non-existent package: " + service.getPackageName());
164 }
165 // Write null to the cache so we don't keep querying PM.
166 si = null;
167 }
168 mServiceInfoCache.add(userId, service, si);
169
170 return si;
171 }
172
173 @GuardedBy("mLock")
174 private boolean updateComponentEnabledStateLocked(JobStatus jobStatus) {
175 final ServiceInfo service = getServiceInfoLocked(jobStatus);
176
177 if (DEBUG && service == null) {
178 Slog.v(TAG, jobStatus.toShortString() + " component not present");
179 }
180 final ServiceInfo ogService = jobStatus.serviceInfo;
181 jobStatus.serviceInfo = service;
182 return !Objects.equals(ogService, service);
183 }
184
185 @GuardedBy("mLock")
186 private void clearComponentsForPackageLocked(final int userId, final String pkg) {
187 final int uIdx = mServiceInfoCache.indexOfKey(userId);
188 for (int c = mServiceInfoCache.numElementsForKey(userId) - 1; c >= 0; --c) {
189 final ComponentName cn = mServiceInfoCache.keyAt(uIdx, c);
190 if (cn.getPackageName().equals(pkg)) {
191 mServiceInfoCache.delete(userId, cn);
192 }
193 }
194 }
195
196 private void updateComponentStateForPackage(final int userId, final String pkg) {
197 synchronized (mLock) {
198 clearComponentsForPackageLocked(userId, pkg);
199 updateComponentStatesLocked(jobStatus -> {
200 // Using user ID instead of source user ID because the service will run under the
201 // user ID, not source user ID.
202 return jobStatus.getUserId() == userId
203 && jobStatus.getServiceComponent().getPackageName().equals(pkg);
204 });
205 }
206 }
207
208 private void updateComponentStateForUser(final int userId) {
209 synchronized (mLock) {
210 mServiceInfoCache.delete(userId);
211 updateComponentStatesLocked(jobStatus -> {
212 // Using user ID instead of source user ID because the service will run under the
213 // user ID, not source user ID.
214 return jobStatus.getUserId() == userId;
215 });
216 }
217 }
218
219 @GuardedBy("mLock")
220 private void updateComponentStatesLocked(@NonNull Predicate<JobStatus> filter) {
221 mComponentStateUpdateFunctor.reset();
222 mService.getJobStore().forEachJob(filter, mComponentStateUpdateFunctor);
223 if (mComponentStateUpdateFunctor.mChangedJobs.size() > 0) {
224 mStateChangedListener.onControllerStateChanged(
225 mComponentStateUpdateFunctor.mChangedJobs);
226 }
227 }
228
229 final class ComponentStateUpdateFunctor implements Consumer<JobStatus> {
230 @GuardedBy("mLock")
231 final ArraySet<JobStatus> mChangedJobs = new ArraySet<>();
232
233 @Override
234 @GuardedBy("mLock")
235 public void accept(JobStatus jobStatus) {
236 if (updateComponentEnabledStateLocked(jobStatus)) {
237 mChangedJobs.add(jobStatus);
238 }
239 }
240
241 @GuardedBy("mLock")
242 private void reset() {
243 mChangedJobs.clear();
244 }
245 }
246
247 @Override
248 @GuardedBy("mLock")
249 public void dumpControllerStateLocked(IndentingPrintWriter pw, Predicate<JobStatus> predicate) {
250 for (int u = 0; u < mServiceInfoCache.numMaps(); ++u) {
251 final int userId = mServiceInfoCache.keyAt(u);
252 for (int p = 0; p < mServiceInfoCache.numElementsForKey(userId); ++p) {
253 final ComponentName componentName = mServiceInfoCache.keyAt(u, p);
254 pw.print(userId);
255 pw.print("-");
256 pw.print(componentName);
257 pw.print(": ");
258 pw.print(mServiceInfoCache.valueAt(u, p));
259 pw.println();
260 }
261 }
262 }
263
264 @Override
265 @GuardedBy("mLock")
266 public void dumpControllerStateLocked(ProtoOutputStream proto, long fieldId,
267 Predicate<JobStatus> predicate) {
268
269 }
270 }