[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Bug#401561: kdelibs: kio_http_cache_cleaner causes thrashing



Package: kdelibs
Version: 4:3.5.5a.dfsg.1-3
Severity: important

I recently switched to Konqueror and noticed that the system would peg 
CPU+disk for up to 2-3 minutes at a time for no apparent reason.  'top' 
indicated that the CPU was 98% in I/O with kswapd being listed high, 
but 'free' reported only 8MB swap used out of 390MB and 700MB+ memory used 
as 'cache' .  I also noticed that this only occurred while 
kio_http_cache_cleaner was running.  This surprises me because my cache size 
is set to 500MB but only 200MB is used:  the cache cleaner shouldn't even be 
doing anything.

A search on google for "kio_http_cache_cleaner swap" lead to this thread 
http://rudd-o.com/wp-commentsrss2.php?p=1204 which indicates others have seen 
the same behavior.  It appears that the root problem is not really 
http_cache_cleaner but its interaction with the Linux kernel's I/O caching 
system.  I am on a custom-built kernel 2.6.16.  (Debian default options but 
with bigmem enabled for use with CMUCL.)

I have modified http_cache_cleaner.cpp to do the following:

1.  Check the size of the cache first before sorting the list of files by 
date.  If the cache has room to grow, exit immediately.

2.  Purge the cache down to 80% of the maximum rather than purge it down only 
to the limit.  This should reduce the number of times it has to run total.

3.  Also do not sort the list of files if the user has requested 
the --clear-all option.

Attached are both diff and patched source file.  I formally declare this patch 
public domain in case upstream wishes to use it in whole or part.

So far it appears to be working on my system.

Severity listed as important because this does seriously impact my work.

KDE:

$ dpkg -p kdelibs
Package: kdelibs
Priority: optional
Section: libs
Installed-Size: 52
Maintainer: Debian Qt/KDE Maintainers <debian-qt-kde@lists.debian.org>
Architecture: all
Version: 4:3.5.5a.dfsg.1-3
Depends: kdelibs4c2a (>= 4:3.5.5a.dfsg.1-3), kdelibs-data (>= 
4:3.5.5a.dfsg.1-3)
Size: 33084
Description: core libraries from the official KDE release
 KDE (the K Desktop Environment) is a powerful Open Source graphical
 desktop environment for Unix workstations. It combines ease of use,
 contemporary functionality, and outstanding graphical design with the
 technological superiority of the Unix operating system.
 .
 This metapackage includes the core KDE libraries, binaries, and data,
 needed by virtually all KDE applications. It does not include
 development files.

Kernel:

$ dpkg -p linux-image-2.6.16-2-686
Package: linux-image-2.6.16-2-686
Priority: optional
Section: base
Installed-Size: 44112
Maintainer: Debian Kernel Team <debian-kernel@lists.debian.org>
Architecture: i386
Source: linux-2.6.16
Version: 2.6.16-17
Provides: linux-image, linux-image-2.6
Depends: module-init-tools (>= 0.9.13), initramfs-tools (>= 0.53) | yaird (>= 
0.0.12-8) | linux-initramfs-tool
Recommends: libc6-i686
Suggests: linux-doc-2.6.16 | linux-source-2.6.16, grub (>= 0.97-3) | lilo (>= 
19.1)
Conflicts: grub (<= 0.95+cvs20040624-17)
Size: 15714646
Description: Linux kernel 2.6.16 image on PPro/Celeron/PII/PIII/P4 machines
 This package provides the binary image and pre-built loadable modules for
 Linux kernel 2.6.16 on Pentium Pro/Celeron/Pentium II/Pentium III/Pentium
 4 machines.


/*
This file is part of KDE

 Copyright (C) 1999-2000 Waldo Bastian (bastian@kde.org)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//----------------------------------------------------------------------------
//
// KDE Http Cache cleanup tool
// $Id: http_cache_cleaner.cpp 362866 2004-11-14 10:54:13Z mueller $

#include <time.h>
#include <stdlib.h>

#include <qdir.h>
#include <qstring.h>
#include <qptrlist.h>

#include <kinstance.h>
#include <klocale.h>
#include <kcmdlineargs.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <dcopclient.h>
#include <kprotocolmanager.h>

#include <unistd.h>

#include <kdebug.h>

time_t currentDate;
int m_maxCacheAge;
int m_maxCacheSize;

static const char appName[] = "kio_http_cache_cleaner";

static const char description[] = I18N_NOOP("KDE HTTP cache maintenance tool");

static const char version[] = "1.0.0";

static const KCmdLineOptions options[] =
{
   {"clear-all", I18N_NOOP("Empty the cache"), 0},
   KCmdLineLastOption
};

struct FileInfo {
   QString name;
   int size; // Size in Kb.
   int age;
};

template class QPtrList<FileInfo>;

class FileInfoList : public QPtrList<FileInfo>
{
public:
   FileInfoList() : QPtrList<FileInfo>() { }
   int compareItems(QPtrCollection::Item item1, QPtrCollection::Item item2)
      { return ((FileInfo *)item1)->age - ((FileInfo *)item2)->age; }
};

// !START OF SYNC!
// Keep the following in sync with the cache code in http.cc
#define CACHE_REVISION "7\n"

FileInfo *readEntry( const QString &filename)
{
   QCString CEF = QFile::encodeName(filename);
   FILE *fs = fopen( CEF.data(), "r");
   if (!fs)
      return 0;

   char buffer[401];
   bool ok = true;

  // CacheRevision
  if (ok && (!fgets(buffer, 400, fs)))
      ok = false;
   if (ok && (strcmp(buffer, CACHE_REVISION) != 0))
      ok = false;

   // Full URL
   if (ok && (!fgets(buffer, 400, fs)))
      ok = false;

   time_t creationDate;
   int age =0;

   // Creation Date
   if (ok && (!fgets(buffer, 400, fs)))
      ok = false;
   if (ok)
   {
      creationDate = (time_t) strtoul(buffer, 0, 10);
      age = (int) difftime(currentDate, creationDate);
      if ( m_maxCacheAge && ( age > m_maxCacheAge))
      {
         ok = false; // Expired
      }
   }

   // Expiration Date
   if (ok && (!fgets(buffer, 400, fs)))
      ok = false;
   if (ok)
   {
//WABA: It seems I slightly misunderstood the meaning of "Expire:" header.
#if 0
      time_t expireDate;
      expireDate = (time_t) strtoul(buffer, 0, 10);
      if (expireDate && (expireDate < currentDate))
         ok = false; // Expired
#endif
   }

   // ETag
   if (ok && (!fgets(buffer, 400, fs)))
      ok = false;
   if (ok)
   {
      // Ignore ETag
   }

   // Last-Modified
   if (ok && (!fgets(buffer, 400, fs)))
      ok = false;
   if (ok)
   {
      // Ignore Last-Modified
   }


   fclose(fs);
   if (ok)
   {
      FileInfo *info = new FileInfo;
      info->age = age;
      return info;
   }

   unlink( CEF.data());
   return 0;
}
// Keep the above in sync with the cache code in http.cc
// !END OF SYNC!

void scanDirectory(FileInfoList &fileEntries, const QString &name, const QString &strDir)
{
   QDir dir(strDir);
   if (!dir.exists()) return;

   QFileInfoList *newEntries = (QFileInfoList *) dir.entryInfoList();

   if (!newEntries) return; // Directory not accessible ??

   for(QFileInfo *qFileInfo = newEntries->first();
       qFileInfo;
       qFileInfo = newEntries->next())
   {
       if (qFileInfo->isFile())
       {
          FileInfo *fileInfo = readEntry( strDir + "/" + qFileInfo->fileName());
          if (fileInfo)
          {
             fileInfo->name = name + "/" + qFileInfo->fileName();
             fileInfo->size = (qFileInfo->size() + 1023) / 1024;
             fileEntries.append(fileInfo);
          }
       }
   }
}

extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
{
   KLocale::setMainCatalogue("kdelibs");
   KCmdLineArgs::init( argc, argv, appName,
		       I18N_NOOP("KDE HTTP cache maintenance tool"),
		       description, version, true);

   KCmdLineArgs::addCmdLineOptions( options );

   KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

   bool deleteAll = args->isSet("clear-all");

   KInstance ins( appName );

   if (!deleteAll)
   {
      DCOPClient *dcop = new DCOPClient();
      QCString name = dcop->registerAs(appName, false);
      if (!name.isEmpty() && (name != appName))
      {
         fprintf(stderr, "%s: Already running! (%s)\n", appName, name.data());
         return 0;
      }
   }

   currentDate = time(0);
   m_maxCacheAge = KProtocolManager::maxCacheAge();
   m_maxCacheSize = KProtocolManager::maxCacheSize();

   if (deleteAll)
      m_maxCacheSize = -1;

   QString strCacheDir = KGlobal::dirs()->saveLocation("cache", "http");

   QDir cacheDir( strCacheDir );
   if (!cacheDir.exists())
   {
      fprintf(stderr, "%s: '%s' does not exist.\n", appName, strCacheDir.ascii());
      return 0;
   }

   QStringList dirs = cacheDir.entryList( );

   FileInfoList cachedEntries;

   for(QStringList::Iterator it = dirs.begin();
       it != dirs.end();
       it++)
   {
      if ((*it)[0] != '.')
      {
         scanDirectory( cachedEntries, *it, strCacheDir + "/" + *it);
      }
   }

   // KAL:  On my Linux system with 1GB RAM and 390MB swap, kio_http_cache_cleaner
   //       causes the system to thrash heavily in swap, bringing the system to
   //       a crawl.  It "ought" not to, but it does, so I added this check to
   //       ensure thrashing only occurs if it really needs to.
   //
   // All files that were too old were already deleted at the end of readEntry().
   // Before calling cachedEntries.sort(), verify that work actually needs to be done
   // first.
   int totalSize = 0;
   if (m_maxCacheSize > 0)
   {
      for(FileInfo *fileInfo = cachedEntries.first();
          fileInfo;
          fileInfo = cachedEntries.next())
      {
         totalSize += fileInfo->size;
      }
      if (totalSize > m_maxCacheSize)
      {
         // Cache is still too big, so something will need to be deleted.
         // Delete everything down to 20%.
         totalSize = 0;
         m_maxCacheSize = m_maxCacheSize * 4 / 5;
      }
      else
      {
         // Cache has more room to grow, so we are done.
         kdDebug () << appName << ": Current size of cache = " << totalSize << " kB, no recent objects needed to be deleted." << endl;
         return 0;
      }

      // Don't bother sorting if the user requested all files be deleted anyway.
      kdDebug () << appName << ": Before call to cachedEntries.sort()." << endl;
      cachedEntries.sort();
      kdDebug () << appName << ": After call to cachedEntries.sort()." << endl;
   }
   
   int maxCachedSize = m_maxCacheSize / 2;

   for(FileInfo *fileInfo = cachedEntries.first();
       fileInfo;
       fileInfo = cachedEntries.next())
   {
      if (fileInfo->size > maxCachedSize)
      {
         QCString filename = QFile::encodeName( strCacheDir + "/" + fileInfo->name);
         unlink(filename.data());
//         kdDebug () << appName << ": Object too big, deleting '" << filename.data() << "' (" << result<< ")" << endl;
      }
   }

   for(FileInfo *fileInfo = cachedEntries.first();
       fileInfo;
       fileInfo = cachedEntries.next())
   {
      if ((totalSize + fileInfo->size) > m_maxCacheSize)
      {
         QCString filename = QFile::encodeName( strCacheDir + "/" + fileInfo->name);
         unlink(filename.data());
//         kdDebug () << appName << ": Cache too big, deleting '" << filename.data() << "' (" << fileInfo->size << ")" << endl;
      }
      else
      {
         totalSize += fileInfo->size;
// fprintf(stderr, "Keep in cache: %s %d %d total = %d\n", fileInfo->name.ascii(), fileInfo->size, fileInfo->age, totalSize);
      }
   }
   kdDebug () << appName << ": Current size of cache = " << totalSize << " kB." << endl;
   return 0;
}


--- kdelibs-3.5.5a.dfsg.1/kioslave/http/http_cache_cleaner.cpp	2005-09-10 03:26:41.000000000 -0500
+++ http_cache_cleaner.cpp	2006-12-04 08:01:09.000000000 -0600
@@ -243,8 +243,43 @@
       }
    }
 
-   cachedEntries.sort();
+   // KAL:  On my Linux system with 1GB RAM and 390MB swap, kio_http_cache_cleaner
+   //       causes the system to thrash heavily in swap, bringing the system to
+   //       a crawl.  It "ought" not to, but it does, so I added this check to
+   //       ensure thrashing only occurs if it really needs to.
+   //
+   // All files that were too old were already deleted at the end of readEntry().
+   // Before calling cachedEntries.sort(), verify that work actually needs to be done
+   // first.
+   int totalSize = 0;
+   if (m_maxCacheSize > 0)
+   {
+      for(FileInfo *fileInfo = cachedEntries.first();
+          fileInfo;
+          fileInfo = cachedEntries.next())
+      {
+         totalSize += fileInfo->size;
+      }
+      if (totalSize > m_maxCacheSize)
+      {
+         // Cache is still too big, so something will need to be deleted.
+         // Delete everything down to 20%.
+         totalSize = 0;
+         m_maxCacheSize = m_maxCacheSize * 4 / 5;
+      }
+      else
+      {
+         // Cache has more room to grow, so we are done.
+         kdDebug () << appName << ": Current size of cache = " << totalSize << " kB, no recent objects needed to be deleted." << endl;
+         return 0;
+      }
 
+      // Don't bother sorting if the user requested all files be deleted anyway.
+      kdDebug () << appName << ": Before call to cachedEntries.sort()." << endl;
+      cachedEntries.sort();
+      kdDebug () << appName << ": After call to cachedEntries.sort()." << endl;
+   }
+   
    int maxCachedSize = m_maxCacheSize / 2;
 
    for(FileInfo *fileInfo = cachedEntries.first();
@@ -259,8 +294,6 @@
       }
    }
 
-   int totalSize = 0;
-
    for(FileInfo *fileInfo = cachedEntries.first();
        fileInfo;
        fileInfo = cachedEntries.next())

Reply to: