Add a script to cleanup old rails assets
authorTom Hughes <tom@compton.nu>
Mon, 23 Nov 2015 09:23:02 +0000 (09:23 +0000)
committerTom Hughes <tom@compton.nu>
Mon, 23 Nov 2015 09:24:13 +0000 (09:24 +0000)
cookbooks/web/recipes/rails.rb
cookbooks/web/templates/default/cleanup-assets.erb [new file with mode: 0644]
cookbooks/web/templates/default/rails.cron.erb

index 9fab99c..632a627 100644 (file)
@@ -79,6 +79,15 @@ rails_port "www.openstreetmap.org" do
   mapzen_valhalla_key web_passwords["mapzen_valhalla_key"]
 end
 
+package "libjson-xs-perl"
+
+template "/usr/local/bin/cleanup-rails-assets" do
+  source "cleanup-assets.erb"
+  owner "root"
+  group "root"
+  mode 0755
+end
+
 gem_package "apachelogregex"
 gem_package "file-tail"
 
diff --git a/cookbooks/web/templates/default/cleanup-assets.erb b/cookbooks/web/templates/default/cleanup-assets.erb
new file mode 100644 (file)
index 0000000..132c826
--- /dev/null
@@ -0,0 +1,73 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use IO::Dir;
+use IO::File;
+use JSON::XS;
+
+my $root = shift @ARGV;
+
+my $manifest;
+
+if (my $file = IO::File->new("${root}/tmp/manifest.json", "r"))
+{
+    $manifest = decode_json(join("\n", $file->getlines));
+
+    $file->close;
+}
+else
+{
+    die "Can't open ${root}/tmp/manifest.json: $!";
+}
+
+expire_assets($manifest, "${root}/public/assets", "");
+
+exit 0;
+
+sub expire_assets
+{
+    my $manifest = shift;
+    my $assetroot = shift;
+    my $prefix = shift;
+
+    if (my $dir = IO::Dir->new("${assetroot}/${prefix}"))
+    {
+        $prefix = "${prefix}/" unless $prefix eq "";
+
+        while (my $name = $dir->read)
+        {
+            next if $name eq "." || $name eq "..";
+
+            my $path = $name = "${prefix}${name}";
+
+            $name =~ s/\.gz$//;
+
+            if (-d "${assetroot}/${path}")
+            {
+                expire_assets($manifest, $assetroot, $path);
+            }
+            elsif (exists($manifest->{files}->{$name}))
+            {
+                # Still a live asset (with checksum)
+            }
+            elsif (exists($manifest->{assets}->{$name}))
+            {
+                # Still a live asset (without checksum)
+            }
+            elsif (-A "${assetroot}/${path}" > 28)
+            {
+                unlink("${assetroot}/${path}") || die "Can't remove ${assetroot}/${path}: $!";
+            }
+        }
+
+        $dir->close;
+    }
+    else
+    {
+        die "Can't read ${assetroot}/${prefix}: $!";
+    }
+
+    return;
+}
index 35256a2..e34880f 100644 (file)
@@ -2,3 +2,6 @@
 
 # Cleanup temporary directory
 find <%= @directory %>/tmp \( \( -type f -mtime +28 \) -o \( -type d -empty \) \) -delete
+
+# Cleanup assets
+/usr/local/bin/cleanup-rails-assets <%= @directory %>