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 "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/extension_registry_observer.h"
21 #include "extensions/common/extension.h"
22 #include "extensions/common/view_type.h"
28 class DevToolsAgentHost
;
29 class RenderFrameHost
;
34 namespace extensions
{
38 class ExtensionRegistry
;
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
,
46 public ExtensionRegistryObserver
{
48 using ExtensionHostSet
= std::set
<extensions::ExtensionHost
*>;
50 static ProcessManager
* Get(content::BrowserContext
* context
);
51 ~ProcessManager() override
;
53 void RegisterRenderFrameHost(content::WebContents
* web_contents
,
54 content::RenderFrameHost
* render_frame_host
,
55 const Extension
* extension
);
56 void UnregisterRenderFrameHost(content::RenderFrameHost
* render_frame_host
);
58 // Returns the SiteInstance that the given URL belongs to.
59 // TODO(aa): This only returns correct results for extensions and packaged
60 // apps, not hosted apps.
61 virtual scoped_refptr
<content::SiteInstance
> GetSiteInstanceForURL(
64 using FrameSet
= std::set
<content::RenderFrameHost
*>;
65 const FrameSet
GetAllFrames() const;
67 // Returns all RenderFrameHosts that are registered for the specified
69 ProcessManager::FrameSet
GetRenderFrameHostsForExtension(
70 const std::string
& extension_id
);
72 void AddObserver(ProcessManagerObserver
* observer
);
73 void RemoveObserver(ProcessManagerObserver
* observer
);
75 // Creates a new UI-less extension instance. Like CreateViewHost, but not
76 // displayed anywhere. Returns false if no background host can be created,
77 // for example for hosted apps and extensions that aren't enabled in
79 virtual bool CreateBackgroundHost(const Extension
* extension
,
82 // Creates background hosts if the embedder is ready and they are not already
84 void MaybeCreateStartupBackgroundHosts();
86 // Gets the ExtensionHost for the background page for an extension, or null if
87 // the extension isn't running or doesn't have a background page.
88 ExtensionHost
* GetBackgroundHostForExtension(const std::string
& extension_id
);
90 // Returns true if the (lazy) background host for the given extension has
91 // already been sent the unload event and is shutting down.
92 bool IsBackgroundHostClosing(const std::string
& extension_id
);
94 // Returns the extension associated with the specified RenderFrameHost/
95 // WebContents, or null.
96 const Extension
* GetExtensionForRenderFrameHost(
97 content::RenderFrameHost
* render_frame_host
);
98 const Extension
* GetExtensionForWebContents(
99 content::WebContents
* web_contents
);
101 // Getter and setter for the lazy background page's keepalive count. This is
102 // the count of how many outstanding "things" are keeping the page alive.
103 // When this reaches 0, we will begin the process of shutting down the page.
104 // "Things" include pending events, resource loads, and API calls.
105 int GetLazyKeepaliveCount(const Extension
* extension
);
106 void IncrementLazyKeepaliveCount(const Extension
* extension
);
107 void DecrementLazyKeepaliveCount(const Extension
* extension
);
109 // Keeps a background page alive. Unlike IncrementLazyKeepaliveCount, these
110 // impulses will only keep the page alive for a limited amount of time unless
112 void KeepaliveImpulse(const Extension
* extension
);
114 // Triggers a keepalive impulse for a plugin (e.g NaCl).
115 static void OnKeepaliveFromPlugin(int render_process_id
,
117 const std::string
& extension_id
);
119 // Handles a response to the ShouldSuspend message, used for lazy background
121 void OnShouldSuspendAck(const std::string
& extension_id
, uint64 sequence_id
);
123 // Same as above, for the Suspend message.
124 void OnSuspendAck(const std::string
& extension_id
);
126 // Tracks network requests for a given RenderFrameHost, used to know
127 // when network activity is idle for lazy background pages.
128 void OnNetworkRequestStarted(content::RenderFrameHost
* render_frame_host
,
130 void OnNetworkRequestDone(content::RenderFrameHost
* render_frame_host
,
133 // Prevents |extension|'s background page from being closed and sends the
134 // onSuspendCanceled() event to it.
135 void CancelSuspend(const Extension
* extension
);
137 // Called on shutdown to close our extension hosts.
138 void CloseBackgroundHosts();
140 // Sets callbacks for testing keepalive impulse behavior.
141 using ImpulseCallbackForTesting
=
142 base::Callback
<void(const std::string
& extension_id
)>;
143 void SetKeepaliveImpulseCallbackForTesting(
144 const ImpulseCallbackForTesting
& callback
);
145 void SetKeepaliveImpulseDecrementCallbackForTesting(
146 const ImpulseCallbackForTesting
& callback
);
148 // Sets the time in milliseconds that an extension event page can
149 // be idle before it is shut down; must be > 0.
150 static void SetEventPageIdleTimeForTesting(unsigned idle_time_msec
);
152 // Sets the time in milliseconds that an extension event page has
153 // between being notified of its impending unload and that unload
155 static void SetEventPageSuspendingTimeForTesting(
156 unsigned suspending_time_msec
);
158 // Creates a non-incognito instance for tests. |registry| allows unit tests
159 // to inject an ExtensionRegistry that is not managed by the usual
160 // BrowserContextKeyedServiceFactory system.
161 static ProcessManager
* CreateForTesting(content::BrowserContext
* context
,
162 ExtensionRegistry
* registry
);
164 // Creates an incognito-context instance for tests.
165 static ProcessManager
* CreateIncognitoForTesting(
166 content::BrowserContext
* incognito_context
,
167 content::BrowserContext
* original_context
,
168 ExtensionRegistry
* registry
);
170 content::BrowserContext
* browser_context() const { return browser_context_
; }
172 const ExtensionHostSet
& background_hosts() const {
173 return background_hosts_
;
176 bool startup_background_hosts_created_for_test() const {
177 return startup_background_hosts_created_
;
181 static ProcessManager
* Create(content::BrowserContext
* context
);
183 // |context| is incognito pass the master context as |original_context|.
184 // Otherwise pass the same context for both. Pass the ExtensionRegistry for
185 // |context| as |registry|, or override it for testing.
186 ProcessManager(content::BrowserContext
* context
,
187 content::BrowserContext
* original_context
,
188 ExtensionRegistry
* registry
);
190 // Not owned. Also used by IncognitoProcessManager.
191 ExtensionRegistry
* extension_registry_
;
194 friend class ProcessManagerFactory
;
195 friend class ProcessManagerTest
;
197 // content::NotificationObserver:
198 void Observe(int type
,
199 const content::NotificationSource
& source
,
200 const content::NotificationDetails
& details
) override
;
202 // ExtensionRegistryObserver:
203 void OnExtensionLoaded(content::BrowserContext
* browser_context
,
204 const Extension
* extension
) override
;
205 void OnExtensionUnloaded(content::BrowserContext
* browser_context
,
206 const Extension
* extension
,
207 UnloadedExtensionInfo::Reason reason
) override
;
209 // Extra information we keep for each extension's background page.
210 struct BackgroundPageData
;
211 struct ExtensionRenderFrameData
;
212 using BackgroundPageDataMap
= std::map
<ExtensionId
, BackgroundPageData
>;
213 using ExtensionRenderFrames
=
214 std::map
<content::RenderFrameHost
*, ExtensionRenderFrameData
>;
216 // Load all background pages once the profile data is ready and the pages
218 void CreateStartupBackgroundHosts();
220 // Called just after |host| is created so it can be registered in our lists.
221 void OnBackgroundHostCreated(ExtensionHost
* host
);
223 // Close the given |host| iff it's a background page.
224 void CloseBackgroundHost(ExtensionHost
* host
);
226 // If the frame isn't keeping the lazy background page alive, increments the
227 // keepalive count to do so.
228 void AcquireLazyKeepaliveCountForFrame(
229 content::RenderFrameHost
* render_frame_host
);
231 // If the frame is keeping the lazy background page alive, decrements the
232 // keepalive count to stop doing it.
233 void ReleaseLazyKeepaliveCountForFrame(
234 content::RenderFrameHost
* render_frame_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 void OnDevToolsStateChanged(content::DevToolsAgentHost
*, bool attached
);
253 // Unregister RenderFrameHosts and clear background page data for an extension
254 // which has been unloaded.
255 void UnregisterExtension(const std::string
& extension_id
);
257 // Clears background page data for this extension.
258 void ClearBackgroundPageData(const std::string
& extension_id
);
260 content::NotificationRegistrar registrar_
;
262 // The set of ExtensionHosts running viewless background extensions.
263 ExtensionHostSet background_hosts_
;
265 // A SiteInstance related to the SiteInstance for all extensions in
266 // this profile. We create it in such a way that a new
267 // browsing instance is created. This controls process grouping.
268 scoped_refptr
<content::SiteInstance
> site_instance_
;
270 // The browser context associated with the |site_instance_|.
271 content::BrowserContext
* browser_context_
;
273 // Contains all active extension-related RenderFrameHost instances for all
274 // extensions. We also keep a cache of the host's view type, because that
275 // information is not accessible at registration/deregistration time.
276 ExtensionRenderFrames all_extension_frames_
;
278 BackgroundPageDataMap background_page_data_
;
280 // True if we have created the startup set of background hosts.
281 bool startup_background_hosts_created_
;
283 base::Callback
<void(content::DevToolsAgentHost
*, bool)> devtools_callback_
;
285 ImpulseCallbackForTesting keepalive_impulse_callback_for_testing_
;
286 ImpulseCallbackForTesting keepalive_impulse_decrement_callback_for_testing_
;
288 ObserverList
<ProcessManagerObserver
> observer_list_
;
290 // ID Counter used to set ProcessManager::BackgroundPageData close_sequence_id
291 // members. These IDs are tracked per extension in background_page_data_ and
292 // are used to verify that nothing has interrupted the process of closing a
293 // lazy background process.
295 // Any interruption obtains a new ID by incrementing
296 // last_background_close_sequence_id_ and storing it in background_page_data_
297 // for a particular extension. Callbacks and round-trip IPC messages store the
298 // value of the extension's close_sequence_id at the beginning of the process.
299 // Thus comparisons can be done to halt when IDs no longer match.
301 // This counter provides unique IDs even when BackgroundPageData objects are
303 uint64 last_background_close_sequence_id_
;
305 // Must be last member, see doc on WeakPtrFactory.
306 base::WeakPtrFactory
<ProcessManager
> weak_ptr_factory_
;
308 DISALLOW_COPY_AND_ASSIGN(ProcessManager
);
311 } // namespace extensions
313 #endif // EXTENSIONS_BROWSER_PROCESS_MANAGER_H_