Update To 11.40.268.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 "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"
22
23 class GURL;
24
25 namespace content {
26 class BrowserContext;
27 class DevToolsAgentHost;
28 class RenderViewHost;
29 class RenderFrameHost;
30 class SiteInstance;
31 };
32
33 namespace extensions {
34
35 class Extension;
36 class ExtensionHost;
37 class ExtensionRegistry;
38 class ProcessManagerDelegate;
39 class ProcessManagerObserver;
40
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:
47   typedef std::set<extensions::ExtensionHost*> ExtensionHostSet;
48   typedef ExtensionHostSet::const_iterator const_iterator;
49
50   static ProcessManager* Get(content::BrowserContext* context);
51   ~ProcessManager() override;
52
53   const ExtensionHostSet& background_hosts() const {
54     return background_hosts_;
55   }
56
57   typedef std::set<content::RenderViewHost*> ViewSet;
58   const ViewSet GetAllViews() const;
59
60   // The typical observer interface.
61   void AddObserver(ProcessManagerObserver* observer);
62   void RemoveObserver(ProcessManagerObserver* observer);
63
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
67   // Incognito.
68   virtual bool CreateBackgroundHost(const Extension* extension,
69                                     const GURL& url);
70
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);
74
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 content::SiteInstance* GetSiteInstanceForURL(const GURL& url);
79
80   // If the view isn't keeping the lazy background page alive, increments the
81   // keepalive count to do so.
82   void AcquireLazyKeepaliveCountForView(
83       content::RenderViewHost* render_view_host);
84
85   // If the view is keeping the lazy background page alive, decrements the
86   // keepalive count to stop doing it.
87   void ReleaseLazyKeepaliveCountForView(
88       content::RenderViewHost* render_view_host);
89
90   // Unregisters a RenderViewHost as hosting any extension.
91   void UnregisterRenderViewHost(content::RenderViewHost* render_view_host);
92
93   // Returns all RenderViewHosts that are registered for the specified
94   // extension.
95   std::set<content::RenderViewHost*> GetRenderViewHostsForExtension(
96       const std::string& extension_id);
97
98   // Returns the extension associated with the specified RenderViewHost, or
99   // NULL.
100   const Extension* GetExtensionForRenderViewHost(
101       content::RenderViewHost* render_view_host);
102
103   // Returns true if the (lazy) background host for the given extension has
104   // already been sent the unload event and is shutting down.
105   bool IsBackgroundHostClosing(const std::string& extension_id);
106
107   // Getter and setter for the lazy background page's keepalive count. This is
108   // the count of how many outstanding "things" are keeping the page alive.
109   // When this reaches 0, we will begin the process of shutting down the page.
110   // "Things" include pending events, resource loads, and API calls.
111   int GetLazyKeepaliveCount(const Extension* extension);
112   void IncrementLazyKeepaliveCount(const Extension* extension);
113   void DecrementLazyKeepaliveCount(const Extension* extension);
114
115   // Keeps a background page alive. Unlike IncrementLazyKeepaliveCount, these
116   // impulses will only keep the page alive for a limited amount of time unless
117   // called regularly.
118   void KeepaliveImpulse(const Extension* extension);
119
120   // Triggers a keepalive impulse for a plug-in (e.g NaCl).
121   static void OnKeepaliveFromPlugin(int render_process_id,
122                                     int render_frame_id,
123                                     const std::string& extension_id);
124
125   // Handles a response to the ShouldSuspend message, used for lazy background
126   // pages.
127   void OnShouldSuspendAck(const std::string& extension_id, uint64 sequence_id);
128
129   // Same as above, for the Suspend message.
130   void OnSuspendAck(const std::string& extension_id);
131
132   // Tracks network requests for a given RenderFrameHost, used to know
133   // when network activity is idle for lazy background pages.
134   void OnNetworkRequestStarted(content::RenderFrameHost* render_frame_host);
135   void OnNetworkRequestDone(content::RenderFrameHost* render_frame_host);
136
137   // Prevents |extension|'s background page from being closed and sends the
138   // onSuspendCanceled() event to it.
139   void CancelSuspend(const Extension* extension);
140
141   // Creates background hosts if the embedder is ready and they are not already
142   // loaded.
143   void MaybeCreateStartupBackgroundHosts();
144
145   // Called on shutdown to close our extension hosts.
146   void CloseBackgroundHosts();
147
148   // Gets the BrowserContext associated with site_instance_ and all other
149   // related SiteInstances.
150   content::BrowserContext* GetBrowserContext() const;
151
152   // Sets callbacks for testing keepalive impulse behavior.
153   typedef base::Callback<void(const std::string& extension_id)>
154       ImpulseCallbackForTesting;
155   void SetKeepaliveImpulseCallbackForTesting(
156       const ImpulseCallbackForTesting& callback);
157   void SetKeepaliveImpulseDecrementCallbackForTesting(
158       const ImpulseCallbackForTesting& callback);
159
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);
163
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);
169
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);
175
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);
181
182   bool startup_background_hosts_created_for_test() const {
183     return startup_background_hosts_created_;
184   }
185
186  protected:
187   static ProcessManager* Create(content::BrowserContext* context);
188
189   //  |context| is incognito pass the master context as |original_context|.
190   // Otherwise pass the same context for both. Pass the ExtensionRegistry for
191   // |context| as |registry|, or override it for testing.
192   ProcessManager(content::BrowserContext* context,
193                  content::BrowserContext* original_context,
194                  ExtensionRegistry* registry);
195
196   // content::NotificationObserver:
197   void Observe(int type,
198                const content::NotificationSource& source,
199                const content::NotificationDetails& details) override;
200
201   content::NotificationRegistrar registrar_;
202
203   // The set of ExtensionHosts running viewless background extensions.
204   ExtensionHostSet background_hosts_;
205
206   // A SiteInstance related to the SiteInstance for all extensions in
207   // this profile.  We create it in such a way that a new
208   // browsing instance is created.  This controls process grouping.
209   scoped_refptr<content::SiteInstance> site_instance_;
210
211   // Not owned. Also used by IncognitoProcessManager.
212   ExtensionRegistry* extension_registry_;
213
214  private:
215   friend class ProcessManagerFactory;
216   friend class ProcessManagerTest;
217
218   // Extra information we keep for each extension's background page.
219   struct BackgroundPageData;
220   struct ExtensionRenderViewData;
221   typedef std::string ExtensionId;
222   typedef std::map<ExtensionId, BackgroundPageData> BackgroundPageDataMap;
223   typedef std::map<content::RenderViewHost*, ExtensionRenderViewData>
224       ExtensionRenderViews;
225
226   // Load all background pages once the profile data is ready and the pages
227   // should be loaded.
228   void CreateStartupBackgroundHosts();
229
230   // Called just after |host| is created so it can be registered in our lists.
231   void OnBackgroundHostCreated(ExtensionHost* host);
232
233   // Close the given |host| iff it's a background page.
234   void CloseBackgroundHost(ExtensionHost* host);
235
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);
239
240   // Checks if keepalive impulses have occured, and adjusts keep alive count.
241   void OnKeepaliveImpulseCheck();
242
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,
246                                 uint64 sequence_id);
247   void OnLazyBackgroundPageActive(const std::string& extension_id);
248   void CloseLazyBackgroundPageNow(const std::string& extension_id,
249                                   uint64 sequence_id);
250
251   // Potentially registers a RenderViewHost, if it is associated with an
252   // extension. Does nothing if this is not an extension renderer.
253   // Returns true, if render_view_host was registered (it is associated
254   // with an extension).
255   bool RegisterRenderViewHost(content::RenderViewHost* render_view_host);
256
257   // Unregister RenderViewHosts and clear background page data for an extension
258   // which has been unloaded.
259   void UnregisterExtension(const std::string& extension_id);
260
261   // Clears background page data for this extension.
262   void ClearBackgroundPageData(const std::string& extension_id);
263
264   void OnDevToolsStateChanged(content::DevToolsAgentHost*, bool attached);
265
266   // Contains all active extension-related RenderViewHost instances for all
267   // extensions. We also keep a cache of the host's view type, because that
268   // information is not accessible at registration/deregistration time.
269   ExtensionRenderViews all_extension_views_;
270
271   BackgroundPageDataMap background_page_data_;
272
273   // True if we have created the startup set of background hosts.
274   bool startup_background_hosts_created_;
275
276   base::Callback<void(content::DevToolsAgentHost*, bool)> devtools_callback_;
277
278   ImpulseCallbackForTesting keepalive_impulse_callback_for_testing_;
279   ImpulseCallbackForTesting keepalive_impulse_decrement_callback_for_testing_;
280
281   ObserverList<ProcessManagerObserver> observer_list_;
282
283   // ID Counter used to set ProcessManager::BackgroundPageData close_sequence_id
284   // members. These IDs are tracked per extension in background_page_data_ and
285   // are used to verify that nothing has interrupted the process of closing a
286   // lazy background process.
287   //
288   // Any interruption obtains a new ID by incrementing
289   // last_background_close_sequence_id_ and storing it in background_page_data_
290   // for a particular extension. Callbacks and round-trip IPC messages store the
291   // value of the extension's close_sequence_id at the beginning of the process.
292   // Thus comparisons can be done to halt when IDs no longer match.
293   //
294   // This counter provides unique IDs even when BackgroundPageData objects are
295   // reset.
296   uint64 last_background_close_sequence_id_;
297
298   // Must be last member, see doc on WeakPtrFactory.
299   base::WeakPtrFactory<ProcessManager> weak_ptr_factory_;
300
301   DISALLOW_COPY_AND_ASSIGN(ProcessManager);
302 };
303
304 }  // namespace extensions
305
306 #endif  // EXTENSIONS_BROWSER_PROCESS_MANAGER_H_