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 // If the view isn't keeping the lazy background page alive, increments the
81 // keepalive count to do so.
82 void AcquireLazyKeepaliveCountForView(
83 content::RenderViewHost
* render_view_host
);
85 // If the view is keeping the lazy background page alive, decrements the
86 // keepalive count to stop doing it.
87 void ReleaseLazyKeepaliveCountForView(
88 content::RenderViewHost
* render_view_host
);
90 // Unregisters a RenderViewHost as hosting any extension.
91 void UnregisterRenderViewHost(content::RenderViewHost
* render_view_host
);
93 // Returns all RenderViewHosts that are registered for the specified
95 std::set
<content::RenderViewHost
*> GetRenderViewHostsForExtension(
96 const std::string
& extension_id
);
98 // Returns the extension associated with the specified RenderViewHost, or
100 const Extension
* GetExtensionForRenderViewHost(
101 content::RenderViewHost
* render_view_host
);
103 // Returns true if the (lazy) background host for the given extension has
104 // already been sent the unload event and is shutting down.
105 bool IsBackgroundHostClosing(const std::string
& extension_id
);
107 // Getter and setter for the lazy background page's keepalive count. This is
108 // the count of how many outstanding "things" are keeping the page alive.
109 // When this reaches 0, we will begin the process of shutting down the page.
110 // "Things" include pending events, resource loads, and API calls.
111 int GetLazyKeepaliveCount(const Extension
* extension
);
112 void IncrementLazyKeepaliveCount(const Extension
* extension
);
113 void DecrementLazyKeepaliveCount(const Extension
* extension
);
115 // Keeps a background page alive. Unlike IncrementLazyKeepaliveCount, these
116 // impulses will only keep the page alive for a limited amount of time unless
118 void KeepaliveImpulse(const Extension
* extension
);
120 // Triggers a keepalive impulse for a plug-in (e.g NaCl).
121 static void OnKeepaliveFromPlugin(int render_process_id
,
123 const std::string
& extension_id
);
125 // Handles a response to the ShouldSuspend message, used for lazy background
127 void OnShouldSuspendAck(const std::string
& extension_id
, uint64 sequence_id
);
129 // Same as above, for the Suspend message.
130 void OnSuspendAck(const std::string
& extension_id
);
132 // Tracks network requests for a given RenderFrameHost, used to know
133 // when network activity is idle for lazy background pages.
134 void OnNetworkRequestStarted(content::RenderFrameHost
* render_frame_host
);
135 void OnNetworkRequestDone(content::RenderFrameHost
* render_frame_host
);
137 // Prevents |extension|'s background page from being closed and sends the
138 // onSuspendCanceled() event to it.
139 void CancelSuspend(const Extension
* extension
);
141 // Creates background hosts if the embedder is ready and they are not already
143 void MaybeCreateStartupBackgroundHosts();
145 // Called on shutdown to close our extension hosts.
146 void CloseBackgroundHosts();
148 // Gets the BrowserContext associated with site_instance_ and all other
149 // related SiteInstances.
150 content::BrowserContext
* GetBrowserContext() const;
152 // Sets callbacks for testing keepalive impulse behavior.
153 typedef base::Callback
<void(const std::string
& extension_id
)>
154 ImpulseCallbackForTesting
;
155 void SetKeepaliveImpulseCallbackForTesting(
156 const ImpulseCallbackForTesting
& callback
);
157 void SetKeepaliveImpulseDecrementCallbackForTesting(
158 const ImpulseCallbackForTesting
& callback
);
160 // Sets the time in milliseconds that an extension event page can
161 // be idle before it is shut down; must be > 0.
162 static void SetEventPageIdleTimeForTesting(unsigned idle_time_msec
);
164 // Sets the time in milliseconds that an extension event page has
165 // between being notified of its impending unload and that unload
167 static void SetEventPageSuspendingTimeForTesting(
168 unsigned suspending_time_msec
);
170 // Creates a non-incognito instance for tests. |registry| allows unit tests
171 // to inject an ExtensionRegistry that is not managed by the usual
172 // BrowserContextKeyedServiceFactory system.
173 static ProcessManager
* CreateForTesting(content::BrowserContext
* context
,
174 ExtensionRegistry
* registry
);
176 // Creates an incognito-context instance for tests.
177 static ProcessManager
* CreateIncognitoForTesting(
178 content::BrowserContext
* incognito_context
,
179 content::BrowserContext
* original_context
,
180 ExtensionRegistry
* registry
);
182 bool startup_background_hosts_created_for_test() const {
183 return startup_background_hosts_created_
;
187 static ProcessManager
* Create(content::BrowserContext
* context
);
189 // |context| is incognito pass the master context as |original_context|.
190 // Otherwise pass the same context for both. Pass the ExtensionRegistry for
191 // |context| as |registry|, or override it for testing.
192 ProcessManager(content::BrowserContext
* context
,
193 content::BrowserContext
* original_context
,
194 ExtensionRegistry
* registry
);
196 // content::NotificationObserver:
197 void Observe(int type
,
198 const content::NotificationSource
& source
,
199 const content::NotificationDetails
& details
) override
;
201 content::NotificationRegistrar registrar_
;
203 // The set of ExtensionHosts running viewless background extensions.
204 ExtensionHostSet background_hosts_
;
206 // A SiteInstance related to the SiteInstance for all extensions in
207 // this profile. We create it in such a way that a new
208 // browsing instance is created. This controls process grouping.
209 scoped_refptr
<content::SiteInstance
> site_instance_
;
211 // Not owned. Also used by IncognitoProcessManager.
212 ExtensionRegistry
* extension_registry_
;
215 friend class ProcessManagerFactory
;
216 friend class ProcessManagerTest
;
218 // Extra information we keep for each extension's background page.
219 struct BackgroundPageData
;
220 struct ExtensionRenderViewData
;
221 typedef std::string ExtensionId
;
222 typedef std::map
<ExtensionId
, BackgroundPageData
> BackgroundPageDataMap
;
223 typedef std::map
<content::RenderViewHost
*, ExtensionRenderViewData
>
224 ExtensionRenderViews
;
226 // Load all background pages once the profile data is ready and the pages
228 void CreateStartupBackgroundHosts();
230 // Called just after |host| is created so it can be registered in our lists.
231 void OnBackgroundHostCreated(ExtensionHost
* host
);
233 // Close the given |host| iff it's a background page.
234 void CloseBackgroundHost(ExtensionHost
* host
);
236 // Internal implementation of DecrementLazyKeepaliveCount with an
237 // |extension_id| known to have a lazy background page.
238 void DecrementLazyKeepaliveCount(const std::string
& extension_id
);
240 // Checks if keepalive impulses have occured, and adjusts keep alive count.
241 void OnKeepaliveImpulseCheck();
243 // These are called when the extension transitions between idle and active.
244 // They control the process of closing the background page when idle.
245 void OnLazyBackgroundPageIdle(const std::string
& extension_id
,
247 void OnLazyBackgroundPageActive(const std::string
& extension_id
);
248 void CloseLazyBackgroundPageNow(const std::string
& extension_id
,
251 // Potentially registers a RenderViewHost, if it is associated with an
252 // extension. Does nothing if this is not an extension renderer.
253 // Returns true, if render_view_host was registered (it is associated
254 // with an extension).
255 bool RegisterRenderViewHost(content::RenderViewHost
* render_view_host
);
257 // Unregister RenderViewHosts and clear background page data for an extension
258 // which has been unloaded.
259 void UnregisterExtension(const std::string
& extension_id
);
261 // Clears background page data for this extension.
262 void ClearBackgroundPageData(const std::string
& extension_id
);
264 void OnDevToolsStateChanged(content::DevToolsAgentHost
*, bool attached
);
266 // Contains all active extension-related RenderViewHost instances for all
267 // extensions. We also keep a cache of the host's view type, because that
268 // information is not accessible at registration/deregistration time.
269 ExtensionRenderViews all_extension_views_
;
271 BackgroundPageDataMap background_page_data_
;
273 // True if we have created the startup set of background hosts.
274 bool startup_background_hosts_created_
;
276 base::Callback
<void(content::DevToolsAgentHost
*, bool)> devtools_callback_
;
278 ImpulseCallbackForTesting keepalive_impulse_callback_for_testing_
;
279 ImpulseCallbackForTesting keepalive_impulse_decrement_callback_for_testing_
;
281 ObserverList
<ProcessManagerObserver
> observer_list_
;
283 // ID Counter used to set ProcessManager::BackgroundPageData close_sequence_id
284 // members. These IDs are tracked per extension in background_page_data_ and
285 // are used to verify that nothing has interrupted the process of closing a
286 // lazy background process.
288 // Any interruption obtains a new ID by incrementing
289 // last_background_close_sequence_id_ and storing it in background_page_data_
290 // for a particular extension. Callbacks and round-trip IPC messages store the
291 // value of the extension's close_sequence_id at the beginning of the process.
292 // Thus comparisons can be done to halt when IDs no longer match.
294 // This counter provides unique IDs even when BackgroundPageData objects are
296 uint64 last_background_close_sequence_id_
;
298 // Must be last member, see doc on WeakPtrFactory.
299 base::WeakPtrFactory
<ProcessManager
> weak_ptr_factory_
;
301 DISALLOW_COPY_AND_ASSIGN(ProcessManager
);
304 } // namespace extensions
306 #endif // EXTENSIONS_BROWSER_PROCESS_MANAGER_H_