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_
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 "base/time/time.h"
18 #include "components/keyed_service/core/keyed_service.h"
19 #include "content/public/browser/notification_observer.h"
20 #include "content/public/browser/notification_registrar.h"
21 #include "extensions/common/view_type.h"
27 class DevToolsAgentHost
;
29 class RenderFrameHost
;
33 namespace extensions
{
37 class ExtensionRegistry
;
38 class ProcessManagerDelegate
;
39 class ProcessManagerObserver
;
41 // Manages dynamic state of running Chromium extensions. There is one instance
42 // of this class per Profile. OTR Profiles have a separate instance that keeps
43 // track of split-mode extensions only.
44 class ProcessManager
: public KeyedService
,
45 public content::NotificationObserver
{
47 typedef std::set
<extensions::ExtensionHost
*> ExtensionHostSet
;
48 typedef ExtensionHostSet::const_iterator const_iterator
;
50 static ProcessManager
* Get(content::BrowserContext
* context
);
51 ~ProcessManager() override
;
53 const ExtensionHostSet
& background_hosts() const {
54 return background_hosts_
;
57 typedef std::set
<content::RenderViewHost
*> ViewSet
;
58 const ViewSet
GetAllViews() const;
60 // The typical observer interface.
61 void AddObserver(ProcessManagerObserver
* observer
);
62 void RemoveObserver(ProcessManagerObserver
* observer
);
64 // Creates a new UI-less extension instance. Like CreateViewHost, but not
65 // displayed anywhere. Returns false if no background host can be created,
66 // for example for hosted apps and extensions that aren't enabled in
68 virtual bool CreateBackgroundHost(const Extension
* extension
,
71 // Gets the ExtensionHost for the background page for an extension, or NULL if
72 // the extension isn't running or doesn't have a background page.
73 ExtensionHost
* GetBackgroundHostForExtension(const std::string
& extension_id
);
75 // Returns the SiteInstance that the given URL belongs to.
76 // TODO(aa): This only returns correct results for extensions and packaged
77 // apps, not hosted apps.
78 virtual content::SiteInstance
* GetSiteInstanceForURL(const GURL
& url
);
80 // Unregisters a RenderViewHost as hosting any extension.
81 void UnregisterRenderViewHost(content::RenderViewHost
* render_view_host
);
83 // Returns all RenderViewHosts that are registered for the specified
85 std::set
<content::RenderViewHost
*> GetRenderViewHostsForExtension(
86 const std::string
& extension_id
);
88 // Returns the extension associated with the specified RenderViewHost, or
90 const Extension
* GetExtensionForRenderViewHost(
91 content::RenderViewHost
* render_view_host
);
93 // Returns true if the (lazy) background host for the given extension has
94 // already been sent the unload event and is shutting down.
95 bool IsBackgroundHostClosing(const std::string
& extension_id
);
97 // Getter and setter for the lazy background page's keepalive count. This is
98 // the count of how many outstanding "things" are keeping the page alive.
99 // When this reaches 0, we will begin the process of shutting down the page.
100 // "Things" include pending events, resource loads, and API calls.
101 int GetLazyKeepaliveCount(const Extension
* extension
);
102 void IncrementLazyKeepaliveCount(const Extension
* extension
);
103 void DecrementLazyKeepaliveCount(const Extension
* extension
);
105 void IncrementLazyKeepaliveCountForView(
106 content::RenderViewHost
* render_view_host
);
108 // Keeps a background page alive. Unlike IncrementLazyKeepaliveCount, these
109 // impulses will only keep the page alive for a limited amount of time unless
111 void KeepaliveImpulse(const Extension
* extension
);
113 // Triggers a keepalive impulse for a plug-in (e.g NaCl).
114 static void OnKeepaliveFromPlugin(int render_process_id
,
116 const std::string
& extension_id
);
118 // Handles a response to the ShouldSuspend message, used for lazy background
120 void OnShouldSuspendAck(const std::string
& extension_id
, uint64 sequence_id
);
122 // Same as above, for the Suspend message.
123 void OnSuspendAck(const std::string
& extension_id
);
125 // Tracks network requests for a given RenderFrameHost, used to know
126 // when network activity is idle for lazy background pages.
127 void OnNetworkRequestStarted(content::RenderFrameHost
* render_frame_host
);
128 void OnNetworkRequestDone(content::RenderFrameHost
* render_frame_host
);
130 // Prevents |extension|'s background page from being closed and sends the
131 // onSuspendCanceled() event to it.
132 void CancelSuspend(const Extension
* extension
);
134 // Creates background hosts if the embedder is ready and they are not already
136 void MaybeCreateStartupBackgroundHosts();
138 // Called on shutdown to close our extension hosts.
139 void CloseBackgroundHosts();
141 // Gets the BrowserContext associated with site_instance_ and all other
142 // related SiteInstances.
143 content::BrowserContext
* GetBrowserContext() const;
145 // Sets callbacks for testing keepalive impulse behavior.
146 typedef base::Callback
<void(const std::string
& extension_id
)>
147 ImpulseCallbackForTesting
;
148 void SetKeepaliveImpulseCallbackForTesting(
149 const ImpulseCallbackForTesting
& callback
);
150 void SetKeepaliveImpulseDecrementCallbackForTesting(
151 const ImpulseCallbackForTesting
& callback
);
153 // Sets the time in milliseconds that an extension event page can
154 // be idle before it is shut down; must be > 0.
155 static void SetEventPageIdleTimeForTesting(unsigned idle_time_msec
);
157 // Sets the time in milliseconds that an extension event page has
158 // between being notified of its impending unload and that unload
160 static void SetEventPageSuspendingTimeForTesting(
161 unsigned suspending_time_msec
);
163 // Creates a non-incognito instance for tests. |registry| allows unit tests
164 // to inject an ExtensionRegistry that is not managed by the usual
165 // BrowserContextKeyedServiceFactory system.
166 static ProcessManager
* CreateForTesting(content::BrowserContext
* context
,
167 ExtensionRegistry
* registry
);
169 // Creates an incognito-context instance for tests.
170 static ProcessManager
* CreateIncognitoForTesting(
171 content::BrowserContext
* incognito_context
,
172 content::BrowserContext
* original_context
,
173 ExtensionRegistry
* registry
);
175 bool startup_background_hosts_created_for_test() const {
176 return startup_background_hosts_created_
;
180 static ProcessManager
* Create(content::BrowserContext
* context
);
182 // |context| is incognito pass the master context as |original_context|.
183 // Otherwise pass the same context for both. Pass the ExtensionRegistry for
184 // |context| as |registry|, or override it for testing.
185 ProcessManager(content::BrowserContext
* context
,
186 content::BrowserContext
* original_context
,
187 ExtensionRegistry
* registry
);
189 // content::NotificationObserver:
190 void Observe(int type
,
191 const content::NotificationSource
& source
,
192 const content::NotificationDetails
& details
) override
;
194 content::NotificationRegistrar registrar_
;
196 // The set of ExtensionHosts running viewless background extensions.
197 ExtensionHostSet background_hosts_
;
199 // A SiteInstance related to the SiteInstance for all extensions in
200 // this profile. We create it in such a way that a new
201 // browsing instance is created. This controls process grouping.
202 scoped_refptr
<content::SiteInstance
> site_instance_
;
204 // Not owned. Also used by IncognitoProcessManager.
205 ExtensionRegistry
* extension_registry_
;
208 friend class ProcessManagerFactory
;
209 friend class ProcessManagerTest
;
211 // Extra information we keep for each extension's background page.
212 struct BackgroundPageData
;
213 typedef std::string ExtensionId
;
214 typedef std::map
<ExtensionId
, BackgroundPageData
> BackgroundPageDataMap
;
215 typedef std::map
<content::RenderViewHost
*,
216 extensions::ViewType
> ExtensionRenderViews
;
218 // Load all background pages once the profile data is ready and the pages
220 void CreateStartupBackgroundHosts();
222 // Called just after |host| is created so it can be registered in our lists.
223 void OnBackgroundHostCreated(ExtensionHost
* host
);
225 // Close the given |host| iff it's a background page.
226 void CloseBackgroundHost(ExtensionHost
* host
);
228 // Internal implementation of DecrementLazyKeepaliveCount with an
229 // |extension_id| known to have a lazy background page.
230 void DecrementLazyKeepaliveCount(const std::string
& extension_id
);
232 // Checks if keepalive impulses have occured, and adjusts keep alive count.
233 void OnKeepaliveImpulseCheck();
235 // These are called when the extension transitions between idle and active.
236 // They control the process of closing the background page when idle.
237 void OnLazyBackgroundPageIdle(const std::string
& extension_id
,
239 void OnLazyBackgroundPageActive(const std::string
& extension_id
);
240 void CloseLazyBackgroundPageNow(const std::string
& extension_id
,
243 // Potentially registers a RenderViewHost, if it is associated with an
244 // extension. Does nothing if this is not an extension renderer.
245 // Returns true, if render_view_host was registered (it is associated
246 // with an extension).
247 bool RegisterRenderViewHost(content::RenderViewHost
* render_view_host
);
249 // Unregister RenderViewHosts and clear background page data for an extension
250 // which has been unloaded.
251 void UnregisterExtension(const std::string
& extension_id
);
253 // Clears background page data for this extension.
254 void ClearBackgroundPageData(const std::string
& extension_id
);
256 void OnDevToolsStateChanged(content::DevToolsAgentHost
*, bool attached
);
258 // Contains all active extension-related RenderViewHost instances for all
259 // extensions. We also keep a cache of the host's view type, because that
260 // information is not accessible at registration/deregistration time.
261 ExtensionRenderViews all_extension_views_
;
263 BackgroundPageDataMap background_page_data_
;
265 // True if we have created the startup set of background hosts.
266 bool startup_background_hosts_created_
;
268 base::Callback
<void(content::DevToolsAgentHost
*, bool)> devtools_callback_
;
270 ImpulseCallbackForTesting keepalive_impulse_callback_for_testing_
;
271 ImpulseCallbackForTesting keepalive_impulse_decrement_callback_for_testing_
;
273 ObserverList
<ProcessManagerObserver
> observer_list_
;
275 // ID Counter used to set ProcessManager::BackgroundPageData close_sequence_id
276 // members. These IDs are tracked per extension in background_page_data_ and
277 // are used to verify that nothing has interrupted the process of closing a
278 // lazy background process.
280 // Any interruption obtains a new ID by incrementing
281 // last_background_close_sequence_id_ and storing it in background_page_data_
282 // for a particular extension. Callbacks and round-trip IPC messages store the
283 // value of the extension's close_sequence_id at the beginning of the process.
284 // Thus comparisons can be done to halt when IDs no longer match.
286 // This counter provides unique IDs even when BackgroundPageData objects are
288 uint64 last_background_close_sequence_id_
;
290 // Must be last member, see doc on WeakPtrFactory.
291 base::WeakPtrFactory
<ProcessManager
> weak_ptr_factory_
;
293 DISALLOW_COPY_AND_ASSIGN(ProcessManager
);
296 } // namespace extensions
298 #endif // EXTENSIONS_BROWSER_PROCESS_MANAGER_H_