import logging
import datetime
import simplejson as json
from eeagent.util import unmake_id

def beat_it(dashi, CFG, pm, log=logging):

    try:
        beat_msg = make_beat_msg(pm, CFG)
        log.log(logging.DEBUG, "Sending the heartbeat : %s" % (json.dumps(beat_msg)))
        dashi.fire(CFG.pd.name, "heartbeat", message=beat_msg)
    except Exception, ex:
        log.exception("Error Sending the heartbeat : %s" % (str(ex)))

def make_beat_msg(pm, CFG):
    beat_msg = {}
    beat_msg['eeagent_id'] = CFG.eeagent.name

    # include node ID if it is present in config
    node_id = CFG.eeagent.get('node_id')
    if node_id is not None:
        beat_msg['node_id'] = CFG.eeagent.node_id

    beat_msg['timestamp'] = str(datetime.datetime.now())

    beat_processes = []
    # we can have many process managers per eeagent, walk them all to get all the processes
    pm.poll()
    processes = pm.get_all()
    for pname in processes:
        p = processes[pname]
        (name, round) = unmake_id(p.get_name())
        try:
            state = p.get_state()
        except:
            log.exception("Had a problem getting process state")
            raise
        beat_p = {'upid': name, 'round': round, 'state': state, 'msg': p.get_error_message()}
        beat_processes.append(beat_p)
    beat_msg['processes'] = beat_processes
    
    return beat_msg

@@ -8,22 +8,55 @@
 logging%0A
-import
+from datetime import tzinfo, timedelta,
  datetim
@@ -119,16 +119,17 @@
 ake_id%0A%0A
+%0A
 def beat
@@ -460,16 +460,17 @@
 (ex)))%0A%0A
+%0A
 def make
@@ -486,16 +486,29 @@
 (pm, CFG
+, log=logging
 ):%0A    b
@@ -744,59 +744,111 @@
     
-beat_msg%5B'timestamp'%5D = str(datetime.datetime.now()
+# include timestamp in UTC, in iso8601/rfc3339%0A    beat_msg%5B'timestamp'%5D = datetime.now(utc).isoformat(
 )%0A%0A 
@@ -1431,20 +1431,16 @@
 ocesses%0A
-    
 %0A    ret
@@ -1452,8 +1452,272 @@
 eat_msg%0A
+%0A%0A_ZERO = timedelta(0)%0A%0A# WWWWHHHHHYYY is this not in standard library%0A%0A%0Aclass UTC(tzinfo):%0A    %22%22%22UTC%22%22%22%0A%0A    def utcoffset(self, dt):%0A        return _ZERO%0A%0A    def tzname(self, dt):%0A        return %22UTC%22%0A%0A    def dst(self, dt):%0A        return _ZERO%0A%0A%0Autc = UTC()%0A

Change heartbeat format to RFC3339