#!/bin/bash
#
-# Copyright (C) 2009 Google Inc.
+# Copyright (C) 2009, 2010, 2011 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
set -e
-DATA_DIR=@LOCALSTATEDIR@/lib/ganeti
+in_cluster() {
+ [[ -e $DATA_DIR/ssconf_master_node ]]
+}
+
+cleanup_master() {
+ # Return if machine is not part of a cluster
+ in_cluster || return 0
+
+ # Return if queue archive directory doesn't exist
+ [[ -d $QUEUE_ARCHIVE_DIR ]] || return 0
+
+ # Remove old jobs
+ find $QUEUE_ARCHIVE_DIR -mindepth 2 -type f -mtime +$REMOVE_AFTER -print0 | \
+ xargs -r0 rm -vf
+}
+
+cleanup_node() {
+ # Return if directory for crypto keys doesn't exist
+ [[ -d $CRYPTO_DIR ]] || return 0
+
+ find $CRYPTO_DIR -mindepth 1 -maxdepth 1 -type d | \
+ while read dir; do
+ if $CHECK_CERT_EXPIRED $dir/cert; then
+ rm -vf $dir/{cert,key}
+ rmdir -v --ignore-fail-on-non-empty $dir
+ fi
+ done
+}
+
+cleanup_watcher() {
+ # Return if machine is not part of a cluster
+ in_cluster || return 0
+
+ # Remove old watcher files
+ find $DATA_DIR -maxdepth 1 -type f -mtime +$REMOVE_AFTER \
+ \( -name 'watcher.*-*-*-*.data' -or \
+ -name 'watcher.*-*-*-*.instance-status' \) -print0 | \
+ xargs -r0 rm -vf
+}
+
+# Overridden by unittest
+: ${LOCALSTATEDIR:=@LOCALSTATEDIR@}
+: ${CHECK_CERT_EXPIRED:=@PKGLIBDIR@/check-cert-expired}
+
+DATA_DIR=$LOCALSTATEDIR/lib/ganeti
+CLEANER_LOG_DIR=$LOCALSTATEDIR/log/ganeti/cleaner
QUEUE_ARCHIVE_DIR=$DATA_DIR/queue/archive
+CRYPTO_DIR=$LOCALSTATEDIR/run/ganeti/crypto
# Define how many days archived jobs should be left alone
REMOVE_AFTER=21
-# Exit if machine is not part of a cluster
-[[ -e $DATA_DIR/ssconf_master_node ]] || echo 0
+# Define how many log files to keep around (usually one per day)
+KEEP_LOGS=50
+
+# Log file for this run
+LOG_FILE=$CLEANER_LOG_DIR/cleaner-$(date +'%Y-%m-%dT%H_%M').$$.log
+
+# Create log directory
+mkdir -p $CLEANER_LOG_DIR
+
+# Redirect all output to log file
+exec >>$LOG_FILE 2>&1
+
+echo "Cleaner started at $(date)"
-# Exit if queue archive directory doesn't exist
-[[ -d $QUEUE_ARCHIVE_DIR ]] || exit 0
+# Remove old cleaner log files
+find $CLEANER_LOG_DIR -maxdepth 1 -type f | sort | head -n -$KEEP_LOGS | \
+xargs -r rm -vf
-# Remove old jobs
-find $QUEUE_ARCHIVE_DIR -mindepth 2 -type f -mtime +$REMOVE_AFTER -print0 | \
-xargs -r0 rm -f
+cleanup_master
+cleanup_node
+cleanup_watcher
exit 0