Reporting number of files as a Drupal status item

Submitted by John on Sat, 07/11/2020 - 14:57

Lately I've been spending a lot of time working with the Feeds module in Drupal, especially dealing with this issue, where using the module on a site in a containerized load-balanced set up can cause problems accessing temporary files. The work around is to just use a different directory for your temporary files. But that comes with some caveats. When you use the systems temporary files directory, e.g. /tmp, you don't need to worry about removing files afterwards, since usually the system will handle that automatically. 

So after applying the above workaround to the Feeds module, I quickly discovered that I was accumulating files that were never deleted in the tmp directory. We wrote a script to purge those periodically, but I also wanted to keep an eye on that directory so I could tell if these started to accumulate again. I can't just go in and inspect via ssh in an environment like Pantheon's, so I ended up writing a very simple hook_requirements implementation in Drupal to provide this information on the admin status page. 

Using the Requirements system in this way is easy, and can be used to generate all sorts of status information about a site. The Information provided by default will probably satisfy 99% of people's needs. But odd items like this can be easily made into a report like this.

/**
 * Implements hook_requirements
 *
 * Add some reporting information to the /admin/reports page about this site
 */
function my_module_requirements($phase){

  $requirements = [];
  if ($phase === 'runtime') {
    // Get the number of temporary files in the feeds directory. These tend to accumulate.
    $path = \Drupal::config('system.file')->get('path.temporary');
    $fi = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS);
    $count = iterator_count($fi);
    $requirements['my_module_tmp_files'] = [
      'title' => 'Temporary directory files',
      'description' => number_format($count),
      'severity' => REQUIREMENT_INFO,
    ];
  }
  return $requirements;
}

I do have to credit this stack overflow post for how to actually get the count of files in a directory.

 

This will add a status page entry that looks like this: 

TEMPORARY DIRECTORY FILES 1,270,745

...yes, I had over 1.2 million files there...