Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / extensions / browser / process_manager.h
blob2b7b64fb7c1f248ff29fe4fc10bcdcc1fa386b30
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef EXTENSIONS_BROWSER_PROCESS_MANAGER_H_
6 #define EXTENSIONS_BROWSER_PROCESS_MANAGER_H_
8 #include <map>
9 #include <set>
10 #include <string>
12 #include "base/callback.h"
13 #include "base/compiler_specific.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/observer_list.h"
17 #include "components/keyed_service/core/keyed_service.h"
18 #include "content/public/browser/notification_observer.h"
19 #include "content/public/browser/notification_registrar.h"
20 #include "extensions/browser/event_page_tracker.h"
21 #include "extensions/browser/extension_registry_observer.h"
22 #include "extensions/common/extension.h"
23 #include "extensions/common/view_type.h"
25 class GURL;
27 namespace content {
28 class BrowserContext;
29 class DevToolsAgentHost;
30 class RenderFrameHost;
31 class SiteInstance;
32 class WebContents;
35 namespace extensions {
37 class Extension;
38 class ExtensionHost;
39 class ExtensionRegistry;
40 class ProcessManagerObserver;
42 // Manages dynamic state of running Chromium extensions. There is one instance
43 // of this class per Profile. OTR Profiles have a separate instance that keeps
44 // track of split-mode extensions only.
45 class ProcessManager : public KeyedService,
46 public content::NotificationObserver,
47 public ExtensionRegistryObserver,
48 public EventPageTracker {
49 public:
50 using ExtensionHostSet = std::set<extensions::ExtensionHost*>;
52 static ProcessManager* Get(content::BrowserContext* context);
53 ~ProcessManager() override;
55 void RegisterRenderFrameHost(content::WebContents* web_contents,
56 content::RenderFrameHost* render_frame_host,
57 const Extension* extension);
58 void UnregisterRenderFrameHost(content::RenderFrameHost* render_frame_host);
60 // Returns the SiteInstance that the given URL belongs to.
61 // TODO(aa): This only returns correct results for extensions and packaged
62 // apps, not hosted apps.
63 virtual scoped_refptr<content::SiteInstance> GetSiteInstanceForURL(
64 const GURL& url);
66 using FrameSet = std::set<content::RenderFrameHost*>;
67 const FrameSet GetAllFrames() const;
69 // Returns all RenderFrameHosts that are registered for the specified
70 // extension.
71 ProcessManager::FrameSet GetRenderFrameHostsForExtension(
72 const std::string& extension_id);
74 void AddObserver(ProcessManagerObserver* observer);
75 void RemoveObserver(ProcessManagerObserver* observer);
77 // Creates a new UI-less extension instance. Like CreateViewHost, but not
78 // displayed anywhere. Returns false if no background host can be created,
79 // for example for hosted apps and extensions that aren't enabled in
80 // Incognito.
81 virtual bool CreateBackgroundHost(const Extension* extension,
82 const GURL& url);
84 // Creates background hosts if the embedder is ready and they are not already
85 // loaded.
86 void MaybeCreateStartupBackgroundHosts();
88 // Gets the ExtensionHost for the background page for an extension, or null if
89 // the extension isn't running or doesn't have a background page.
90 ExtensionHost* GetBackgroundHostForExtension(const std::string& extension_id);
92 // Returns true if the (lazy) background host for the given extension has
93 // already been sent the unload event and is shutting down.
94 bool IsBackgroundHostClosing(const std::string& extension_id);
96 // Returns the extension associated with the specified RenderFrameHost/
97 // WebContents, or null.
98 const Extension* GetExtensionForRenderFrameHost(
99 content::RenderFrameHost* render_frame_host);
100 const Extension* GetExtensionForWebContents(
101 content::WebContents* web_contents);
103 // Getter and setter for the lazy background page's keepalive count. This is
104 // the count of how many outstanding "things" are keeping the page alive.
105 // When this reaches 0, we will begin the process of shutting down the page.
106 // "Things" include pending events, resource loads, and API calls.
107 int GetLazyKeepaliveCount(const Extension* extension);
108 void IncrementLazyKeepaliveCount(const Extension* extension);
109 void DecrementLazyKeepaliveCount(const Extension* extension);
111 // Keeps a background page alive. Unlike IncrementLazyKeepaliveCount, these
112 // impulses will only keep the page alive for a limited amount of time unless
113 // called regularly.
114 void KeepaliveImpulse(const Extension* extension);
116 // Triggers a keepalive impulse for a plugin (e.g NaCl).
117 static void OnKeepaliveFromPlugin(int render_process_id,
118 int render_frame_id,
119 const std::string& extension_id);
121 // Handles a response to the ShouldSuspend message, used for lazy background
122 // pages.
123 void OnShouldSuspendAck(const std::string& extension_id, uint64 sequence_id);
125 // Same as above, for the Suspend message.
126 void OnSuspendAck(const std::string& extension_id);
128 // Tracks network requests for a given RenderFrameHost, used to know
129 // when network activity is idle for lazy background pages.
130 void OnNetworkRequestStarted(content::RenderFrameHost* render_frame_host,
131 uint64 request_id);
132 void OnNetworkRequestDone(content::RenderFrameHost* render_frame_host,
133 uint64 request_id);
135 // Prevents |extension|'s background page from being closed and sends the
136 // onSuspendCanceled() event to it.
137 void CancelSuspend(const Extension* extension);
139 // Called on shutdown to close our extension hosts.
140 void CloseBackgroundHosts();
142 // Sets callbacks for testing keepalive impulse behavior.
143 using ImpulseCallbackForTesting =
144 base::Callback<void(const std::string& extension_id)>;
145 void SetKeepaliveImpulseCallbackForTesting(
146 const ImpulseCallbackForTesting& callback);
147 void SetKeepaliveImpulseDecrementCallbackForTesting(
148 const ImpulseCallbackForTesting& callback);
150 // EventPageTracker implementation.
151 bool IsEventPageSuspended(const std::string& extension_id) override;
152 bool WakeEventPage(const std::string& extension_id,
153 const base::Callback<void(bool)>& callback) override;
155 // Sets the time in milliseconds that an extension event page can
156 // be idle before it is shut down; must be > 0.
157 static void SetEventPageIdleTimeForTesting(unsigned idle_time_msec);
159 // Sets the time in milliseconds that an extension event page has
160 // between being notified of its impending unload and that unload
161 // happening.
162 static void SetEventPageSuspendingTimeForTesting(
163 unsigned suspending_time_msec);
165 // Creates a non-incognito instance for tests. |registry| allows unit tests
166 // to inject an ExtensionRegistry that is not managed by the usual
167 // BrowserContextKeyedServiceFactory system.
168 static ProcessManager* CreateForTesting(content::BrowserContext* context,
169 ExtensionRegistry* registry);
171 // Creates an incognito-context instance for tests.
172 static ProcessManager* CreateIncognitoForTesting(
173 content::BrowserContext* incognito_context,
174 content::BrowserContext* original_context,
175 ExtensionRegistry* registry);
177 content::BrowserContext* browser_context() const { return browser_context_; }
179 const ExtensionHostSet& background_hosts() const {
180 return background_hosts_;
183 bool startup_background_hosts_created_for_test() const {
184 return startup_background_hosts_created_;
187 protected:
188 static ProcessManager* Create(content::BrowserContext* context);
190 // |context| is incognito pass the master context as |original_context|.
191 // Otherwise pass the same context for both. Pass the ExtensionRegistry for
192 // |context| as |registry|, or override it for testing.
193 ProcessManager(content::BrowserContext* context,
194 content::BrowserContext* original_context,
195 ExtensionRegistry* registry);
197 // Not owned. Also used by IncognitoProcessManager.
198 ExtensionRegistry* extension_registry_;
200 private:
201 friend class ProcessManagerFactory;
202 friend class ProcessManagerTest;
204 // content::NotificationObserver:
205 void Observe(int type,
206 const content::NotificationSource& source,
207 const content::NotificationDetails& details) override;
209 // ExtensionRegistryObserver:
210 void OnExtensionLoaded(content::BrowserContext* browser_context,
211 const Extension* extension) override;
212 void OnExtensionUnloaded(content::BrowserContext* browser_context,
213 const Extension* extension,
214 UnloadedExtensionInfo::Reason reason) override;
216 // Extra information we keep for each extension's background page.
217 struct BackgroundPageData;
218 struct ExtensionRenderFrameData;
219 using BackgroundPageDataMap = std::map<ExtensionId, BackgroundPageData>;
220 using ExtensionRenderFrames =
221 std::map<content::RenderFrameHost*, ExtensionRenderFrameData>;
223 // Load all background pages once the profile data is ready and the pages
224 // should be loaded.
225 void CreateStartupBackgroundHosts();
227 // Called just after |host| is created so it can be registered in our lists.
228 void OnBackgroundHostCreated(ExtensionHost* host);
230 // Close the given |host| iff it's a background page.
231 void CloseBackgroundHost(ExtensionHost* host);
233 // If the frame isn't keeping the lazy background page alive, increments the
234 // keepalive count to do so.
235 void AcquireLazyKeepaliveCountForFrame(
236 content::RenderFrameHost* render_frame_host);
238 // If the frame is keeping the lazy background page alive, decrements the
239 // keepalive count to stop doing it.
240 void ReleaseLazyKeepaliveCountForFrame(
241 content::RenderFrameHost* render_frame_host);
243 // Internal implementation of DecrementLazyKeepaliveCount with an
244 // |extension_id| known to have a lazy background page.
245 void DecrementLazyKeepaliveCount(const std::string& extension_id);
247 // Checks if keepalive impulses have occured, and adjusts keep alive count.
248 void OnKeepaliveImpulseCheck();
250 // These are called when the extension transitions between idle and active.
251 // They control the process of closing the background page when idle.
252 void OnLazyBackgroundPageIdle(const std::string& extension_id,
253 uint64 sequence_id);
254 void OnLazyBackgroundPageActive(const std::string& extension_id);
255 void CloseLazyBackgroundPageNow(const std::string& extension_id,
256 uint64 sequence_id);
258 void OnDevToolsStateChanged(content::DevToolsAgentHost*, bool attached);
260 // Unregister RenderFrameHosts and clear background page data for an extension
261 // which has been unloaded.
262 void UnregisterExtension(const std::string& extension_id);
264 // Clears background page data for this extension.
265 void ClearBackgroundPageData(const std::string& extension_id);
267 content::NotificationRegistrar registrar_;
269 // The set of ExtensionHosts running viewless background extensions.
270 ExtensionHostSet background_hosts_;
272 // A SiteInstance related to the SiteInstance for all extensions in
273 // this profile. We create it in such a way that a new
274 // browsing instance is created. This controls process grouping.
275 scoped_refptr<content::SiteInstance> site_instance_;
277 // The browser context associated with the |site_instance_|.
278 content::BrowserContext* browser_context_;
280 // Contains all active extension-related RenderFrameHost instances for all
281 // extensions. We also keep a cache of the host's view type, because that
282 // information is not accessible at registration/deregistration time.
283 ExtensionRenderFrames all_extension_frames_;
285 BackgroundPageDataMap background_page_data_;
287 // True if we have created the startup set of background hosts.
288 bool startup_background_hosts_created_;
290 base::Callback<void(content::DevToolsAgentHost*, bool)> devtools_callback_;
292 ImpulseCallbackForTesting keepalive_impulse_callback_for_testing_;
293 ImpulseCallbackForTesting keepalive_impulse_decrement_callback_for_testing_;
295 ObserverList<ProcessManagerObserver> observer_list_;
297 // ID Counter used to set ProcessManager::BackgroundPageData close_sequence_id
298 // members. These IDs are tracked per extension in background_page_data_ and
299 // are used to verify that nothing has interrupted the process of closing a
300 // lazy background process.
302 // Any interruption obtains a new ID by incrementing
303 // last_background_close_sequence_id_ and storing it in background_page_data_
304 // for a particular extension. Callbacks and round-trip IPC messages store the
305 // value of the extension's close_sequence_id at the beginning of the process.
306 // Thus comparisons can be done to halt when IDs no longer match.
308 // This counter provides unique IDs even when BackgroundPageData objects are
309 // reset.
310 uint64 last_background_close_sequence_id_;
312 // Must be last member, see doc on WeakPtrFactory.
313 base::WeakPtrFactory<ProcessManager> weak_ptr_factory_;
315 DISALLOW_COPY_AND_ASSIGN(ProcessManager);
318 } // namespace extensions
320 #endif // EXTENSIONS_BROWSER_PROCESS_MANAGER_H_