Shut down the ServiceWorker system as the browser's shutting down.

This avoids a DCHECK in ProfileDestroyer::DestroyProfileWhenAppropriate.

I also added a Chrome-side browsertest for the Service Worker system, where we
can check other things that only show up with this embedder.

I tried to move the DCHECK into ~BrowserContext so that we wouldn't need to
expose the Terminate() function across the Content API, but:
* BrowserContext doesn't know whether it's a "testing" profile.
* There is no BrowserContext::GetOffTheRecordProfile with which to check that
  transitive processes have been shut down.
* (Minor) GetHostsForProfile() works by iterating over all hosts, and moving the
  DCHECK to ~BrowserContext would have doubled the number of iterations needed.

BUG=368570

Review URL: https://codereview.chromium.org/305723003

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@273741 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc
index a4e35338..2ea7e75 100644
--- a/chrome/browser/browser_process_impl.cc
+++ b/chrome/browser/browser_process_impl.cc
@@ -86,6 +86,8 @@
 #include "content/public/browser/plugin_service.h"
 #include "content/public/browser/render_process_host.h"
 #include "content/public/browser/resource_dispatcher_host.h"
+#include "content/public/browser/service_worker_context.h"
+#include "content/public/browser/storage_partition.h"
 #include "extensions/common/constants.h"
 #include "extensions/common/extension_l10n_util.h"
 #include "net/socket/client_socket_pool_manager.h"
@@ -325,6 +327,10 @@
   return module_ref_count_;
 }
 
+static void ShutdownServiceWorkerContext(content::StoragePartition* partition) {
+  partition->GetServiceWorkerContext()->Terminate();
+}
+
 unsigned int BrowserProcessImpl::ReleaseModule() {
   DCHECK(CalledOnValidThread());
   DCHECK_NE(0u, module_ref_count_);
@@ -332,6 +338,14 @@
   if (0 == module_ref_count_) {
     release_last_reference_callstack_ = base::debug::StackTrace();
 
+    // Stop service workers
+    ProfileManager* pm = profile_manager();
+    std::vector<Profile*> profiles(pm->GetLoadedProfiles());
+    for (size_t i = 0; i < profiles.size(); ++i) {
+      content::BrowserContext::ForEachStoragePartition(
+          profiles[i], base::Bind(ShutdownServiceWorkerContext));
+    }
+
 #if defined(ENABLE_PRINTING)
     // Wait for the pending print jobs to finish. Don't do this later, since
     // this might cause a nested message loop to run, and we don't want pending