Extension syncing: Introduce a NeedsSync pref
[chromium-blink-merge.git] / extensions / browser / process_manager.h
blob85f2defa286f403fae88f88d04574eee77780dcb
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_
8 #include <map>
9 #include <set>
10 #include <string>
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/event_page_tracker.h"
21 #include "extensions/browser/extension_registry_observer.h"
22 #include "extensions/common/extension.h"
23 #include "extensions/common/view_type.h"
25 class GURL;
27 namespace content {
28 class BrowserContext;
29 class DevToolsAgentHost;
30 class RenderFrameHost;
31 class SiteInstance;
32 class WebContents;
35 namespace extensions {
37 class Extension;
38 class ExtensionHost;
39 class ExtensionRegistry;
40 class ProcessManagerObserver;
42 // Manages dynamic state of running Chromium extensions. There is one instance
43 // of this class per Profile. OTR Profiles have a separate instance that keeps
44 // track of split-mode extensions only.
45 class ProcessManager : public KeyedService,
46 public content::NotificationObserver,
47 public ExtensionRegistryObserver,
48 public EventPageTracker {
49 public:
50 using ExtensionHostSet = std::set<extensions::ExtensionHost*>;
52 static ProcessManager* Get(content::BrowserContext* context);
53 ~ProcessManager() override;
55 void RegisterRenderFrameHost(content::WebContents* web_contents,
56 content::RenderFrameHost* render_frame_host,
57 const Extension* extension);
58 void UnregisterRenderFrameHost(content::RenderFrameHost* render_frame_host);
60 // Returns the SiteInstance that the given URL belongs to.
61 // TODO(aa): This only returns correct results for extensions and packaged
62 // apps, not hosted apps.
63 virtual scoped_refptr<content::SiteInstance> GetSiteInstanceForURL(
64 const GURL& url);
66 using FrameSet = std::set<content::RenderFrameHost*>;
67 const FrameSet GetAllFrames() const;
69 // Returns all RenderFrameHosts that are registered for the specified
70 // extension.
71 ProcessManager::FrameSet GetRenderFrameHostsForExtension(
72 const std::string& extension_id);
74 void AddObserver(ProcessManagerObserver* observer);
75 void RemoveObserver(ProcessManagerObserver* observer);
77 // Creates a new UI-less extension instance. Like CreateViewHost, but not
78 // displayed anywhere. Returns false if no background host can be created,
79 // for example for hosted apps and extensions that aren't enabled in
80 // Incognito.
81 virtual bool CreateBackgroundHost(const Extension* extension,
82 const GURL& url);
84 // Creates background hosts if the embedder is ready and they are not already
85 // loaded.
86 void MaybeCreateStartupBackgroundHosts();
88 // Gets the ExtensionHost for the background page for an extension, or null if
89 // the extension isn't running or doesn't have a background page.
90 ExtensionHost* GetBackgroundHostForExtension(const std::string& extension_id);
92 // Returns the ExtensionHost for the given |render_frame_host|, if there is
93 // one.
94 ExtensionHost* GetExtensionHostForRenderFrameHost(
95 content::RenderFrameHost* render_frame_host);
97 // Returns true if the (lazy) background host for the given extension has
98 // already been sent the unload event and is shutting down.
99 bool IsBackgroundHostClosing(const std::string& extension_id);
101 // Returns the extension associated with the specified RenderFrameHost/
102 // WebContents, or null.
103 const Extension* GetExtensionForRenderFrameHost(
104 content::RenderFrameHost* render_frame_host);
105 const Extension* GetExtensionForWebContents(
106 const content::WebContents* web_contents);
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
118 // called regularly.
119 void KeepaliveImpulse(const Extension* extension);
121 // Triggers a keepalive impulse for a plugin (e.g NaCl).
122 static void OnKeepaliveFromPlugin(int render_process_id,
123 int render_frame_id,
124 const std::string& extension_id);
126 // Handles a response to the ShouldSuspend message, used for lazy background
127 // pages.
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,
136 uint64 request_id);
137 void OnNetworkRequestDone(content::RenderFrameHost* render_frame_host,
138 uint64 request_id);
140 // Prevents |extension|'s background page from being closed and sends the
141 // onSuspendCanceled() event to it.
142 void CancelSuspend(const Extension* extension);
144 // Called on shutdown to close our extension hosts.
145 void CloseBackgroundHosts();
147 // Sets callbacks for testing keepalive impulse behavior.
148 using ImpulseCallbackForTesting =
149 base::Callback<void(const std::string& extension_id)>;
150 void SetKeepaliveImpulseCallbackForTesting(
151 const ImpulseCallbackForTesting& callback);
152 void SetKeepaliveImpulseDecrementCallbackForTesting(
153 const ImpulseCallbackForTesting& callback);
155 // EventPageTracker implementation.
156 bool IsEventPageSuspended(const std::string& extension_id) override;
157 bool WakeEventPage(const std::string& extension_id,
158 const base::Callback<void(bool)>& callback) override;
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
166 // happening.
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 content::BrowserContext* browser_context() const { return browser_context_; }
184 const ExtensionHostSet& background_hosts() const {
185 return background_hosts_;
188 bool startup_background_hosts_created_for_test() const {
189 return startup_background_hosts_created_;
192 protected:
193 static ProcessManager* Create(content::BrowserContext* context);
195 // |context| is incognito pass the master context as |original_context|.
196 // Otherwise pass the same context for both. Pass the ExtensionRegistry for
197 // |context| as |registry|, or override it for testing.
198 ProcessManager(content::BrowserContext* context,
199 content::BrowserContext* original_context,
200 ExtensionRegistry* registry);
202 // Not owned. Also used by IncognitoProcessManager.
203 ExtensionRegistry* extension_registry_;
205 private:
206 friend class ProcessManagerFactory;
207 friend class ProcessManagerTest;
209 // content::NotificationObserver:
210 void Observe(int type,
211 const content::NotificationSource& source,
212 const content::NotificationDetails& details) override;
214 // ExtensionRegistryObserver:
215 void OnExtensionLoaded(content::BrowserContext* browser_context,
216 const Extension* extension) override;
217 void OnExtensionUnloaded(content::BrowserContext* browser_context,
218 const Extension* extension,
219 UnloadedExtensionInfo::Reason reason) override;
221 // Extra information we keep for each extension's background page.
222 struct BackgroundPageData;
223 struct ExtensionRenderFrameData;
224 using BackgroundPageDataMap = std::map<ExtensionId, BackgroundPageData>;
225 using ExtensionRenderFrames =
226 std::map<content::RenderFrameHost*, ExtensionRenderFrameData>;
228 // Load all background pages once the profile data is ready and the pages
229 // should be loaded.
230 void CreateStartupBackgroundHosts();
232 // Called just after |host| is created so it can be registered in our lists.
233 void OnBackgroundHostCreated(ExtensionHost* host);
235 // Close the given |host| iff it's a background page.
236 void CloseBackgroundHost(ExtensionHost* host);
238 // If the frame isn't keeping the lazy background page alive, increments the
239 // keepalive count to do so.
240 void AcquireLazyKeepaliveCountForFrame(
241 content::RenderFrameHost* render_frame_host);
243 // If the frame is keeping the lazy background page alive, decrements the
244 // keepalive count to stop doing it.
245 void ReleaseLazyKeepaliveCountForFrame(
246 content::RenderFrameHost* render_frame_host);
248 // Internal implementation of DecrementLazyKeepaliveCount with an
249 // |extension_id| known to have a lazy background page.
250 void DecrementLazyKeepaliveCount(const std::string& extension_id);
252 // Checks if keepalive impulses have occured, and adjusts keep alive count.
253 void OnKeepaliveImpulseCheck();
255 // These are called when the extension transitions between idle and active.
256 // They control the process of closing the background page when idle.
257 void OnLazyBackgroundPageIdle(const std::string& extension_id,
258 uint64 sequence_id);
259 void OnLazyBackgroundPageActive(const std::string& extension_id);
260 void CloseLazyBackgroundPageNow(const std::string& extension_id,
261 uint64 sequence_id);
263 void OnDevToolsStateChanged(content::DevToolsAgentHost*, bool attached);
265 // Unregister RenderFrameHosts and clear background page data for an extension
266 // which has been unloaded.
267 void UnregisterExtension(const std::string& extension_id);
269 // Clears background page data for this extension.
270 void ClearBackgroundPageData(const std::string& extension_id);
272 content::NotificationRegistrar registrar_;
274 // The set of ExtensionHosts running viewless background extensions.
275 ExtensionHostSet background_hosts_;
277 // A SiteInstance related to the SiteInstance for all extensions in
278 // this profile. We create it in such a way that a new
279 // browsing instance is created. This controls process grouping.
280 scoped_refptr<content::SiteInstance> site_instance_;
282 // The browser context associated with the |site_instance_|.
283 content::BrowserContext* browser_context_;
285 // Contains all active extension-related RenderFrameHost instances for all
286 // extensions. We also keep a cache of the host's view type, because that
287 // information is not accessible at registration/deregistration time.
288 ExtensionRenderFrames all_extension_frames_;
290 BackgroundPageDataMap background_page_data_;
292 // True if we have created the startup set of background hosts.
293 bool startup_background_hosts_created_;
295 base::Callback<void(content::DevToolsAgentHost*, bool)> devtools_callback_;
297 ImpulseCallbackForTesting keepalive_impulse_callback_for_testing_;
298 ImpulseCallbackForTesting keepalive_impulse_decrement_callback_for_testing_;
300 base::ObserverList<ProcessManagerObserver> observer_list_;
302 // ID Counter used to set ProcessManager::BackgroundPageData close_sequence_id
303 // members. These IDs are tracked per extension in background_page_data_ and
304 // are used to verify that nothing has interrupted the process of closing a
305 // lazy background process.
307 // Any interruption obtains a new ID by incrementing
308 // last_background_close_sequence_id_ and storing it in background_page_data_
309 // for a particular extension. Callbacks and round-trip IPC messages store the
310 // value of the extension's close_sequence_id at the beginning of the process.
311 // Thus comparisons can be done to halt when IDs no longer match.
313 // This counter provides unique IDs even when BackgroundPageData objects are
314 // reset.
315 uint64 last_background_close_sequence_id_;
317 // Must be last member, see doc on WeakPtrFactory.
318 base::WeakPtrFactory<ProcessManager> weak_ptr_factory_;
320 DISALLOW_COPY_AND_ASSIGN(ProcessManager);
323 } // namespace extensions
325 #endif // EXTENSIONS_BROWSER_PROCESS_MANAGER_H_