#!/usr/bin/perl -w
# Telegraf exec plugin to collect posftix mailq stats and output influxdb compatible datas

use strict;
use JSON;

open (INSTANCES, '/usr/sbin/postmulti -l|') or die "Can't list postfix instances\n";

my @instances;
while (<INSTANCES>) {
	chomp($_);
	my ($name, $group, $status, $directory) =  split /\s+/;
	push @instances, { 
			Name => $name, 
			Group => $group, 
			Status => $status, 
			Directory => $directory 
	};
}
close(INSTANCES);

foreach my $instance (@instances) {
	open (QUEUE, "/usr/sbin/postmulti -i $instance->{Name} -x /usr/sbin/postqueue -j|");
	if ( $? != 0 ) {
		warn "Instance $instance->{Name}, unable to get queue stats: $!\n";
		next;
	}
	my $data;
	while (<QUEUE>) {
		my $json = JSON->new->allow_nonref;
		my $mesg = $json->decode($_);
		if ( $mesg ) {
			push @$data, $mesg;
		} else {
			warn "Instance $instance->{Name}, unable to read json from $json\n";
			next;
		}
	}
	my $stats;
	foreach my $mail (@$data) {
		$stats->{$mail->{queue_name}}->{mail_count}++;
		$stats->{$mail->{queue_name}}->{mail_bytes} += $mail->{message_size};
	}
	foreach my $queue (keys %$stats) {
		printf("postfix,instance=%s,queue=%s mails_count=%d,mails_bytes=%d\n", $instance->{Name}, $queue, $stats->{$queue}->{mail_count}, $stats->{$queue}->{mail_bytes});
	}
}

