# -*- encoding: utf8 -*-
# A daemon to keep SSH forwarding connected
from __future__ import print_function, absolute_import

import os
import sys
import time
import socket
import logging


class Daemon(object):
    def __init__(self):
        self.heartbeat = 50

    def 
(self):
        logging.basicConfig(filename='daemon.log')
        logging.error('daemon started')
        self.daemonize()

        while True:
            if not self.check_connection():
                self.reconnect()
                logging.warn('reconnecting')
            time.sleep(self.heartbeat)

    def check_connection(self):
        c = socket.socket()
        try:
            c.connect(('localhost', 3366))
            c.close()
            return True
        except socket.error:
            return False

    def daemonize(self):
        pid = os.fork()
        if pid:
            os.waitpid(pid, os.WNOHANG)
            sys.exit(0)
        return

    def reconnect(self):
        pid = os.fork()
        if pid == 0:  # child
            err = os.execlp('/usr/bin/ssh', 'ssh', '-i',
                            '/home/xu/.ssh/id_rsa', '-L',
                            '3366:127.0.0.1:3306', '-p', '42022', 'xu@abc.com')
            if err:
                logging.error("error to execlp")
                sys.exit(1)
        elif pid > 0:
            os.waitpid(pid, 0)
        else:
            logging.error('error to fork')
            sys.exit(2)


if __name__ == '__main__':
    Daemon().run()

run