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