import subprocess
import rospy
import traceback
import sys


class KmlAlive:
    def __init__(self, earth_proc):
        self.earth_proc = earth_proc
        rospy.loginfo("XXX starting KMLALIVE process")
        self.timeout_period = rospy.get_param('~timeout_period', 5)
        self.initial_timeout = rospy.get_param('~initial_timeout', 60)
        rospy.Timer(rospy.Duration(10), self.keep_alive, oneshot=True)
        # only restart when worked is true, otherwise
        # it may have never worked
        self.worked = False

    def keep_alive(self, *args, **kwargs):
        try:
            self._keep_alive(args, kwargs)
        except Exception as e:
            rospy.logerr("exception was {} {} {}".format(e, traceback.format_exc(), sys.exc_info()[0]))
            rospy.sleep(1)
            self.keep_alive(args, kwargs)

    def _keep_alive(self, *args, **kwargs):
        rospy.logerr("XXX in first keep_alive")
        loop_timeout = 1
        counter = 0
        rospy.sleep(1)
        with open('/dev/null', 'w') as dev_null:
            while not rospy.is_shutdown():
                try:
                    pid = self.earth_proc.proc.watcher.proc.pid
                except AttributeError as e:
                    counter = 0
                    rospy.logwarn("Earth proc doesn't exist {}".format(e))
                    rospy.sleep(loop_timeout)
                    continue
                cmd = "lsof -Pn -p {} -a -i @127.0.0.1:8765".format(pid).split(' ')
                ret_value = subprocess.call(
                    cmd,
                    stdout=dev_null,
                    stderr=dev_null,
                    close_fds=True
                )
                if ret_value == 0:
                    self.worked = True
                    counter = 0
                else:
                    counter += 1
                    rospy.logerr("XXX found non zero value for {} counter at {}".format(pid, counter))
                    if (counter > self.timeout_period and self.worked) or counter > self.initial_timeout:
                        rospy.logerr("XXX RELAUNCHING worked: {}  counter: {}".format(self.worked, counter))
                        self.earth_proc.handle_soft_relaunch()
                        counter = 0
                        self.worked = False
                rospy.sleep(loop_timeout)

@@ -573,313 +573,8 @@
 s):%0A
-        try:%0A            self._keep_alive(args, kwargs)%0A        except Exception as e:%0A            rospy.logerr(%22exception was %7B%7D %7B%7D %7B%7D%22.format(e, traceback.format_exc(), sys.exc_info()%5B0%5D))%0A            rospy.sleep(1)%0A            self.keep_alive(args, kwargs)%0A%0A    def _keep_alive(self, *args, **kwargs):%0A
     
@@ -689,61 +689,8 @@
 (1)%0A
-        with open('/dev/null', 'w') as dev_null:%0A    
     
@@ -740,21 +740,13 @@
     
- 
-   
 try:%0A
-    
     
@@ -813,20 +813,16 @@
         
- 
-   
 except A
@@ -849,36 +849,32 @@
                 
-    
 counter = 0%0A    
@@ -877,36 +877,32 @@
                 
- 
-   
 rospy.logwarn(%22E
@@ -948,36 +948,32 @@
                 
-    
 rospy.sleep(loop
@@ -998,20 +998,16 @@
         
- 
-   
 continue
@@ -1007,20 +1007,16 @@
 ontinue%0A
-    
         
@@ -1099,20 +1099,16 @@
         
-    
 ret_valu
@@ -1144,20 +1144,16 @@
         
-    
 cmd,%0A   
@@ -1169,33 +1169,35 @@
     
- 
-   
 stdout=
-dev_null,%0A    
+subprocess.DEVNULL,%0A
     
@@ -1219,22 +1219,28 @@
 err=
-dev_null,%0A    
+subprocess.DEVNULL,%0A
     
@@ -1278,20 +1278,16 @@
         
-    
 )%0A      
@@ -1292,20 +1292,16 @@
         
- 
-   
 if ret_v
@@ -1311,20 +1311,16 @@
 e == 0:%0A
-    
         
@@ -1354,36 +1354,32 @@
                 
- 
-   
 counter = 0%0A    
@@ -1386,20 +1386,16 @@
         
-    
 else:%0A  
@@ -1400,36 +1400,32 @@
                 
- 
-   
 counter += 1%0A   
@@ -1417,28 +1417,24 @@
 ounter += 1%0A
-    
             
@@ -1536,20 +1536,16 @@
         
- 
-   
 if (coun
@@ -1634,36 +1634,32 @@
                 
-    
 rospy.logerr(%22XX
@@ -1743,28 +1743,24 @@
             
- 
-   
 self.earth_p
@@ -1798,36 +1798,32 @@
                 
-    
 counter = 0%0A    
@@ -1830,36 +1830,32 @@
                 
- 
-   
 self.worked = Fa
@@ -1858,20 +1858,16 @@
 = False%0A
-    
         

Clean up KmlAlive