Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / extensions / browser / process_manager.h
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.
4
5 #ifndef EXTENSIONS_BROWSER_PROCESS_MANAGER_H_
6 #define EXTENSIONS_BROWSER_PROCESS_MANAGER_H_
7
8 #include <map>
9 #include <set>
10 #include <string>
11
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"
21
22 class GURL;
23
24 namespace content {
25 class BrowserContext;
26 class DevToolsAgentHost;
27 class RenderViewHost;
28 class RenderFrameHost;
29 class SiteInstance;
30 };
31
32 namespace extensions {
33
34 class Extension;
35 class ExtensionHost;
36 class ExtensionRegistry;
37 class ProcessManagerDelegate;
38 class ProcessManagerObserver;
39
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 {
44  public:
45   typedef std::set<extensions::ExtensionHost*> ExtensionHostSet;
46   typedef ExtensionHostSet::const_iterator const_iterator;
47
48   static ProcessManager* Create(content::BrowserContext* context);
49   virtual ~ProcessManager();
50
51   const ExtensionHostSet& background_hosts() const {
52     return background_hosts_;
53   }
54
55   typedef std::set<content::RenderViewHost*> ViewSet;
56   const ViewSet GetAllViews() const;
57
58   // The typical observer interface.
59   void AddObserver(ProcessManagerObserver* observer);
60   void RemoveObserver(ProcessManagerObserver* observer);
61
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
65   // Incognito.
66   virtual bool CreateBackgroundHost(const Extension* extension,
67                                     const GURL& url);
68
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);
72
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);
77
78   // Unregisters a RenderViewHost as hosting any extension.
79   void UnregisterRenderViewHost(content::RenderViewHost* render_view_host);
80
81   // Returns all RenderViewHosts that are registered for the specified
82   // extension.
83   std::set<content::RenderViewHost*> GetRenderViewHostsForExtension(
84       const std::string& extension_id);
85
86   // Returns the extension associated with the specified RenderViewHost, or
87   // NULL.
88   const Extension* GetExtensionForRenderViewHost(
89       content::RenderViewHost* render_view_host);
90
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);
94
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);
102
103   void IncrementLazyKeepaliveCountForView(
104       content::RenderViewHost* render_view_host);
105
106   // Keeps a background page alive. Unlike IncrementLazyKeepaliveCount, these
107   // impulses will only keep the page alive for a limited amount of time unless
108   // called regularly.
109   void KeepaliveImpulse(const Extension* extension);
110
111   // Handles a response to the ShouldSuspend message, used for lazy background
112   // pages.
113   void OnShouldSuspendAck(const std::string& extension_id, uint64 sequence_id);
114
115   // Same as above, for the Suspend message.
116   void OnSuspendAck(const std::string& extension_id);
117
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);
122
123   // Prevents |extension|'s background page from being closed and sends the
124   // onSuspendCanceled() event to it.
125   void CancelSuspend(const Extension* extension);
126
127   // Creates background hosts if the embedder is ready and they are not already
128   // loaded.
129   void MaybeCreateStartupBackgroundHosts();
130
131   // Called on shutdown to close our extension hosts.
132   void CloseBackgroundHosts();
133
134   // Gets the BrowserContext associated with site_instance_ and all other
135   // related SiteInstances.
136   content::BrowserContext* GetBrowserContext() const;
137
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);
145
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);
151
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);
158
159   bool startup_background_hosts_created_for_test() const {
160     return startup_background_hosts_created_;
161   }
162
163  protected:
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);
170
171   // content::NotificationObserver:
172   virtual void Observe(int type,
173                        const content::NotificationSource& source,
174                        const content::NotificationDetails& details) OVERRIDE;
175
176   content::NotificationRegistrar registrar_;
177
178   // The set of ExtensionHosts running viewless background extensions.
179   ExtensionHostSet background_hosts_;
180
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_;
185
186   // Not owned. Also used by IncognitoProcessManager.
187   ExtensionRegistry* extension_registry_;
188
189  private:
190   friend class ProcessManagerTest;
191
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;
198
199   // Load all background pages once the profile data is ready and the pages
200   // should be loaded.
201   void CreateStartupBackgroundHosts();
202
203   // Called just after |host| is created so it can be registered in our lists.
204   void OnBackgroundHostCreated(ExtensionHost* host);
205
206   // Close the given |host| iff it's a background page.
207   void CloseBackgroundHost(ExtensionHost* host);
208
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);
212
213   // Checks if keepalive impulses have occured, and adjusts keep alive count.
214   void OnKeepaliveImpulseCheck();
215
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,
219                                 uint64 sequence_id);
220   void OnLazyBackgroundPageActive(const std::string& extension_id);
221   void CloseLazyBackgroundPageNow(const std::string& extension_id,
222                                   uint64 sequence_id);
223
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);
229
230   // Unregister RenderViewHosts and clear background page data for an extension
231   // which has been unloaded.
232   void UnregisterExtension(const std::string& extension_id);
233
234   // Clears background page data for this extension.
235   void ClearBackgroundPageData(const std::string& extension_id);
236
237   void OnDevToolsStateChanged(content::DevToolsAgentHost*, bool attached);
238
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_;
243
244   BackgroundPageDataMap background_page_data_;
245
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_;
249
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_;
253
254   // True if we have created the startup set of background hosts.
255   bool startup_background_hosts_created_;
256
257   base::Callback<void(content::DevToolsAgentHost*, bool)> devtools_callback_;
258
259   ImpulseCallbackForTesting keepalive_impulse_callback_for_testing_;
260   ImpulseCallbackForTesting keepalive_impulse_decrement_callback_for_testing_;
261
262   ObserverList<ProcessManagerObserver> observer_list_;
263
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.
268   //
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.
274   //
275   // This counter provides unique IDs even when BackgroundPageData objects are
276   // reset.
277   uint64 last_background_close_sequence_id_;
278
279   // Must be last member, see doc on WeakPtrFactory.
280   base::WeakPtrFactory<ProcessManager> weak_ptr_factory_;
281
282   DISALLOW_COPY_AND_ASSIGN(ProcessManager);
283 };
284
285 }  // namespace extensions
286
287 #endif  // EXTENSIONS_BROWSER_PROCESS_MANAGER_H_