#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Filename: master.py

# -----------------------------------
# Revision:     2.0
# Date:         2017-11-06
# Author:       mpdesign
# description:  主服务
# -----------------------------------


from core.include import *
import readline
from bin.scopy import *


# 启动
def start(params):
    jname = params["job"]
    ps = ''
    for p in params["dicts"]:
        ps = "%s -%s %s" % (ps, p, params["dicts"][p])
    cmd = "%s/slave start %s %s" % (PATH_CONFIG["project_path"], jname, ps)
    distribute(cmd)
    output('All slave has started ')


# 停止
def stop(params):
    jname = params["job"]
    ps = ''
    for p in params["dicts"]:
        ps = "%s -%s %s" % (ps, p, params["dicts"][p])
    cmd = "%s/slave stop %s %s" % (PATH_CONFIG["project_path"], jname, ps)
    distribute(cmd)
    output('All slave has stopped')


# 重启
def restart(params):

    jname = params["job"]
    ps = ''
    for p in params["dicts"]:
        ps = "%s -%s %s" % (ps, p, params["dicts"][p])
    #start job
    timeout = 6 if jname == 'r2m' else 3
    cmd = "%s/slave stop %s %s" % (PATH_CONFIG["project_path"], jname, ps)
    distribute(cmd, timeout=timeout)
    output('All slave has stoppped')
    cmd = "%s/slave start %s %s" % (PATH_CONFIG["project_path"], jname, ps)
    distribute(cmd, timeout=timeout)
    output('All slave has started')


def importBin(bin_name, params):
    import_bin = "from bin.%s import * " % bin_name
    exec(import_bin)
    return executeBin(params)


def distribute(cmd, timeout=3):
    singleton.getinstance('ptelnet').timeout(timeout).ssh2(action='ssh', host=SLAVE_NODE, command=[cmd])


actions = {'start': start, 'stop': stop, 'restart': restart}


# 执行动作
def switchAction(params):
    action_name = params['argvs'][1]
    job_name = params['argvs'][2]
    if not job_name:
        output('Job is null')
    else:
        actions.get(action_name)(params)
    logFile = "%s/%s/%s/%s" % (PATH_CONFIG['log_path'], time.strftime('%Y', time.localtime()), time.strftime('%m', time.localtime()), time.strftime('%d', time.localtime()))
    output('LogFile Dir: ' + logFile)


if __name__ == '__main__':
    # 只允许master节点运行该程序
    if not isMaster():
        output("Current node is not master")
        sys.exit(0)
    if len(sys.argv) < 3:
        print "gflow 2.0 @mpdesign (python2.7, r1168, %s) " % time.strftime('%b %d %Y, %H:%M:%S', time.localtime())
        print 'Type "help" for more information.'
        print '    ______    ____________      _________                 __'
        print '   / ____/   / _______,/ /     / ___,\ \/                / /'
        print '  / /       / / ____  / /     / /    /\ \     _____     / /'
        print ' / /   ___ / _____/  / /     / /    / /\ \   / / \ \   / /'
        print ' \ \____/ / /       / /_____/ /____/ /  \ \_/ /   \ \_/ /'
        print '  \_____,/_/       /______,/________/    \___/     \___/ '
        print ''
        if len(sys.argv) == 2:
            del sys.argv[1]
        action_name = ''
        catalog_name = ''
        schema_name = ''
        while True:
            input_action = ':' + action_name if action_name else ''
            input_schema = ':' + schema_name if schema_name else ''
            input_catalog = ':' + catalog_name if catalog_name else ''
            ipt = raw_input("gflow%s%s%s > " % (input_action, input_catalog, input_schema)).strip(' ')
            if not ipt:
                continue
            ipt = ipt.split(' ')
            if ipt[0] == 'exit':
                exit('bye!')
            if ipt[0] == 'q' or ipt[0] == 'quit':
                if schema_name:
                    schema_name = ''
                elif catalog_name:
                    catalog_name = ''
                elif action_name:
                    action_name = ''
                else:
                    exit('bye!')
                continue
            elif not action_name:
                action_name = ipt[0]
                continue
            # catalog connector
            elif ipt[0] == 'catalog':
                if len(ipt) < 2:
                    print 'please input catalog [mysql|hive]'
                    continue
                catalog_name = ipt[1].rstrip(';')
                continue
            # use schema
            elif ipt[0] == 'use':
                if len(ipt) < 2:
                    print 'please input schema'
                    continue
                schema_name = ipt[1].rstrip(';')
                continue
            if catalog_name:
                ipt.append('-catalog')
                ipt.append(catalog_name)
            if schema_name:
                ipt.append('-schema')
                ipt.append(schema_name)
            params = [i.strip() for i in ipt]
            params = getargvs(params)
            bin_file = "%s/bin/%s.py" % (PATH_CONFIG['project_path'], action_name)
            if not singleton.getinstance('pfile').isfile(bin_file):
                output('Bin %s is not valid' % action_name)
            else:
                importBin(action_name, params)

    else:
        params = argv_cli
        # master唯一标识
        _r = "%s%s" % (time.time(), random.randint(0, 1000000))
        params["dicts"]['pid'] = md5(_r)[0:6]
        if "id" in params["dicts"].keys():
            del params["dicts"]['id']

        switchAction(params)