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 "content/public/browser/notification_observer.h"
19 #include "content/public/browser/notification_registrar.h"
20 #include "extensions/common/view_type.h"
26 class DevToolsAgentHost;
28 class RenderFrameHost;
32 namespace extensions {
36 class ExtensionRegistry;
37 class ProcessManagerDelegate;
38 class ProcessManagerObserver;
40 // Manages dynamic state of running Chromium extensions. There is one instance
41 // of this class per Profile. OTR Profiles have a separate instance that keeps
42 // track of split-mode extensions only.
43 class ProcessManager : public content::NotificationObserver {
45 typedef std::set<extensions::ExtensionHost*> ExtensionHostSet;
46 typedef ExtensionHostSet::const_iterator const_iterator;
48 static ProcessManager* Create(content::BrowserContext* context);
49 virtual ~ProcessManager();
51 const ExtensionHostSet& background_hosts() const {
52 return background_hosts_;
55 typedef std::set<content::RenderViewHost*> ViewSet;
56 const ViewSet GetAllViews() const;
58 // The typical observer interface.
59 void AddObserver(ProcessManagerObserver* observer);
60 void RemoveObserver(ProcessManagerObserver* observer);
62 // Creates a new UI-less extension instance. Like CreateViewHost, but not
63 // displayed anywhere. Returns false if no background host can be created,
64 // for example for hosted apps and extensions that aren't enabled in
66 virtual bool CreateBackgroundHost(const Extension* extension,
69 // Gets the ExtensionHost for the background page for an extension, or NULL if
70 // the extension isn't running or doesn't have a background page.
71 ExtensionHost* GetBackgroundHostForExtension(const std::string& extension_id);
73 // Returns the SiteInstance that the given URL belongs to.
74 // TODO(aa): This only returns correct results for extensions and packaged
75 // apps, not hosted apps.
76 virtual content::SiteInstance* GetSiteInstanceForURL(const GURL& url);
78 // Unregisters a RenderViewHost as hosting any extension.
79 void UnregisterRenderViewHost(content::RenderViewHost* render_view_host);
81 // Returns all RenderViewHosts that are registered for the specified
83 std::set<content::RenderViewHost*> GetRenderViewHostsForExtension(
84 const std::string& extension_id);
86 // Returns the extension associated with the specified RenderViewHost, or
88 const Extension* GetExtensionForRenderViewHost(
89 content::RenderViewHost* render_view_host);
91 // Returns true if the (lazy) background host for the given extension has
92 // already been sent the unload event and is shutting down.
93 bool IsBackgroundHostClosing(const std::string& extension_id);
95 // Getter and setter for the lazy background page's keepalive count. This is
96 // the count of how many outstanding "things" are keeping the page alive.
97 // When this reaches 0, we will begin the process of shutting down the page.
98 // "Things" include pending events, resource loads, and API calls.
99 int GetLazyKeepaliveCount(const Extension* extension);
100 void IncrementLazyKeepaliveCount(const Extension* extension);
101 void DecrementLazyKeepaliveCount(const Extension* extension);
103 void IncrementLazyKeepaliveCountForView(
104 content::RenderViewHost* render_view_host);
106 // Keeps a background page alive. Unlike IncrementLazyKeepaliveCount, these
107 // impulses will only keep the page alive for a limited amount of time unless
109 void KeepaliveImpulse(const Extension* extension);
111 // Handles a response to the ShouldSuspend message, used for lazy background
113 void OnShouldSuspendAck(const std::string& extension_id, uint64 sequence_id);
115 // Same as above, for the Suspend message.
116 void OnSuspendAck(const std::string& extension_id);
118 // Tracks network requests for a given RenderFrameHost, used to know
119 // when network activity is idle for lazy background pages.
120 void OnNetworkRequestStarted(content::RenderFrameHost* render_frame_host);
121 void OnNetworkRequestDone(content::RenderFrameHost* render_frame_host);
123 // Prevents |extension|'s background page from being closed and sends the
124 // onSuspendCanceled() event to it.
125 void CancelSuspend(const Extension* extension);
127 // Creates background hosts if the embedder is ready and they are not already
129 void MaybeCreateStartupBackgroundHosts();
131 // Called on shutdown to close our extension hosts.
132 void CloseBackgroundHosts();
134 // Gets the BrowserContext associated with site_instance_ and all other
135 // related SiteInstances.
136 content::BrowserContext* GetBrowserContext() const;
138 // Sets callbacks for testing keepalive impulse behavior.
139 typedef base::Callback<void(const std::string& extension_id)>
140 ImpulseCallbackForTesting;
141 void SetKeepaliveImpulseCallbackForTesting(
142 const ImpulseCallbackForTesting& callback);
143 void SetKeepaliveImpulseDecrementCallbackForTesting(
144 const ImpulseCallbackForTesting& callback);
146 // Creates a non-incognito instance for tests. |registry| allows unit tests
147 // to inject an ExtensionRegistry that is not managed by the usual
148 // BrowserContextKeyedServiceFactory system.
149 static ProcessManager* CreateForTesting(content::BrowserContext* context,
150 ExtensionRegistry* registry);
152 // Creates an incognito-context instance for tests.
153 static ProcessManager* CreateIncognitoForTesting(
154 content::BrowserContext* incognito_context,
155 content::BrowserContext* original_context,
156 ProcessManager* original_manager,
157 ExtensionRegistry* registry);
159 bool startup_background_hosts_created_for_test() const {
160 return startup_background_hosts_created_;
164 // If |context| is incognito pass the master context as |original_context|.
165 // Otherwise pass the same context for both. Pass the ExtensionRegistry for
166 // |context| as |registry|, or override it for testing.
167 ProcessManager(content::BrowserContext* context,
168 content::BrowserContext* original_context,
169 ExtensionRegistry* registry);
171 // content::NotificationObserver:
172 virtual void Observe(int type,
173 const content::NotificationSource& source,
174 const content::NotificationDetails& details) OVERRIDE;
176 content::NotificationRegistrar registrar_;
178 // The set of ExtensionHosts running viewless background extensions.
179 ExtensionHostSet background_hosts_;
181 // A SiteInstance related to the SiteInstance for all extensions in
182 // this profile. We create it in such a way that a new
183 // browsing instance is created. This controls process grouping.
184 scoped_refptr<content::SiteInstance> site_instance_;
186 // Not owned. Also used by IncognitoProcessManager.
187 ExtensionRegistry* extension_registry_;
190 friend class ProcessManagerTest;
192 // Extra information we keep for each extension's background page.
193 struct BackgroundPageData;
194 typedef std::string ExtensionId;
195 typedef std::map<ExtensionId, BackgroundPageData> BackgroundPageDataMap;
196 typedef std::map<content::RenderViewHost*,
197 extensions::ViewType> ExtensionRenderViews;
199 // Load all background pages once the profile data is ready and the pages
201 void CreateStartupBackgroundHosts();
203 // Called just after |host| is created so it can be registered in our lists.
204 void OnBackgroundHostCreated(ExtensionHost* host);
206 // Close the given |host| iff it's a background page.
207 void CloseBackgroundHost(ExtensionHost* host);
209 // Internal implementation of DecrementLazyKeepaliveCount with an
210 // |extension_id| known to have a lazy background page.
211 void DecrementLazyKeepaliveCount(const std::string& extension_id);
213 // Checks if keepalive impulses have occured, and adjusts keep alive count.
214 void OnKeepaliveImpulseCheck();
216 // These are called when the extension transitions between idle and active.
217 // They control the process of closing the background page when idle.
218 void OnLazyBackgroundPageIdle(const std::string& extension_id,
220 void OnLazyBackgroundPageActive(const std::string& extension_id);
221 void CloseLazyBackgroundPageNow(const std::string& extension_id,
224 // Potentially registers a RenderViewHost, if it is associated with an
225 // extension. Does nothing if this is not an extension renderer.
226 // Returns true, if render_view_host was registered (it is associated
227 // with an extension).
228 bool RegisterRenderViewHost(content::RenderViewHost* render_view_host);
230 // Unregister RenderViewHosts and clear background page data for an extension
231 // which has been unloaded.
232 void UnregisterExtension(const std::string& extension_id);
234 // Clears background page data for this extension.
235 void ClearBackgroundPageData(const std::string& extension_id);
237 void OnDevToolsStateChanged(content::DevToolsAgentHost*, bool attached);
239 // Contains all active extension-related RenderViewHost instances for all
240 // extensions. We also keep a cache of the host's view type, because that
241 // information is not accessible at registration/deregistration time.
242 ExtensionRenderViews all_extension_views_;
244 BackgroundPageDataMap background_page_data_;
246 // The time to delay between an extension becoming idle and
247 // sending a ShouldSuspend message; read from command-line switch.
248 base::TimeDelta event_page_idle_time_;
250 // The time to delay between sending a ShouldSuspend message and
251 // sending a Suspend message; read from command-line switch.
252 base::TimeDelta event_page_suspending_time_;
254 // True if we have created the startup set of background hosts.
255 bool startup_background_hosts_created_;
257 base::Callback<void(content::DevToolsAgentHost*, bool)> devtools_callback_;
259 ImpulseCallbackForTesting keepalive_impulse_callback_for_testing_;
260 ImpulseCallbackForTesting keepalive_impulse_decrement_callback_for_testing_;
262 ObserverList<ProcessManagerObserver> observer_list_;
264 // ID Counter used to set ProcessManager::BackgroundPageData close_sequence_id
265 // members. These IDs are tracked per extension in background_page_data_ and
266 // are used to verify that nothing has interrupted the process of closing a
267 // lazy background process.
269 // Any interruption obtains a new ID by incrementing
270 // last_background_close_sequence_id_ and storing it in background_page_data_
271 // for a particular extension. Callbacks and round-trip IPC messages store the
272 // value of the extension's close_sequence_id at the beginning of the process.
273 // Thus comparisons can be done to halt when IDs no longer match.
275 // This counter provides unique IDs even when BackgroundPageData objects are
277 uint64 last_background_close_sequence_id_;
279 // Must be last member, see doc on WeakPtrFactory.
280 base::WeakPtrFactory<ProcessManager> weak_ptr_factory_;
282 DISALLOW_COPY_AND_ASSIGN(ProcessManager);
285 } // namespace extensions
287 #endif // EXTENSIONS_BROWSER_PROCESS_MANAGER_H_