Calculating the time difference between successive timestamps

I have logs for services getting started or stopped. Using the timestamps from these logs I want to calculate the uptime and downtime for services. Here is what I did:
Each time a service is stopped, calculate the uptime by calculating the difference between the current timestamp and the timestamp from the last time that service was running. This gives me for how long the service has been up before the current stopped event. Calculated downtime similarly. So I have uptime values for every stopped event and downtime for every started event. This usually works fine.


In the image, the dicovery is filtered for a single service and there are some negative values for the calculated uptime field. In those cases, the next timestamp is getting reduced from the current rather than the previous timestamp, can't figure out why. The values after them are also inaccurate.
Here is my script:

if([State] == "running")
{
    aggregate
    {
	    task_id  => "%{Service}"
	    code => "map['startedtime'] = event.get('@timestamp')
			     map['stoppedtime'] ||= map['startedtime']
			     event.set('Downtime', ((Time.parse(map['startedtime'].to_s)) - ((Time.parse(map['stoppedtime'].to_s)))))
		         "
    }
}

if([State] == "stopped")
{
    aggregate
    {
	    task_id  => "%{Service}"
	    code => "map['stoppedtime'] = event.get('@timestamp')
			     map['startedtime'] ||= map['stoppedtime']
			     event.set('Uptime', ((Time.parse(map['stoppedtime'].to_s)) - ((Time.parse(map['startedtime'].to_s)))))
			     "
    }
}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.