Beispiel #1
0
def writexmlbyxml(alist):
    """根据alist生成xml,然后让函数  **write_xml** 写入。
    """
    global filetopath
    domaiversion = getversion()
    root = ET.fromstring("<configs> </configs>")
    add_child_subelement(root, create_element("config", {'name': 'server_path', 'value': '/data/release/sgonline'},''))
    add_child_subelement(root, create_element("config", {'name': 'sversion', 'value': domaiversion}, ''))

    if len(alist) > 0:
        dbnum = int(alist[0]['db'])
        res = getresbynum(dbnum)
        if res :
            #res = res.replace("'",'').lstrip('[(').rstrip(')]').split(',')
            res = eval(res)[0]
        else :
            write_logger('error',"CSServer return Num error!!")
            sys.exit(100)

        ip = res[1].strip()

        add_child_subelement(root, create_element("config", {'name':ip,'db':alist[0]['db'],'value': alist[0]['value']},''))

    for line in alist:
        add_child_subelement(root, create_element("config", line,''))
    indent(root)
    write_xml(ET.ElementTree(root),filetopath)
Beispiel #2
0
def getres(astr,host=csip,port=csport):
    """向 socketserver发送一个 *astr* 。
    server采用密码验证,所以需要线进行密码判断,然后再传送 * astr * 字符串。
    收到服务器传送的数据之后,进行长度验证,如果不正确,重新传送。
    判断成功或者失败次数超出限制之后端开连接,返回结果。



    :param astr: 字符串命令
    :param host: 发送命令的server ip。 默认是给CSserver发送,
    :param port: server port。 默认是CSserver 的port。

    """
    time.sleep(1)
    # 1. 参数初始化
    bufsize = 1024
    addr = (host,port)

    # 1. 初始化socket
    client = socket(AF_INET, SOCK_STREAM)
    try:
        client.connect(addr)
    except error,e:
        write_logger('error', 'Connect  CSSERVER ERROR ')
        return None
Beispiel #3
0
def insertnewzone(alist):
    """新插入一个元素(list 操作)
    """
    listitems = gamezones()
    dbnum = alist['db']

    res = getresbynum(dbnum)
    if res:
        #res = res.replace("'",'').lstrip('[(').rstrip(')]').split(',')
        res = eval(res)[0]
    else:
        write_logger('error', "CSServer return Num error!!")
        sys.exit(100)

    dbvalue = res[2].strip()
    dbname = res[3].strip()
    alist = argvToAlist(dbnum, dbvalue, dbname)

    listitems.append(alist)
    astr = "update iswork=1 dbnum=" + str(dbnum)

    res = getres(astr, host=csip)

    write_xml_alist(sortitems(listitems))
    sys.exit()
def getres(astr,host=csip,port=csport):
    """向 socketserver发送一个 *astr* 。
    server采用密码验证,所以需要线进行密码判断,然后再传送 * astr * 字符串。
    收到服务器传送的数据之后,进行长度验证,如果不正确,重新传送。
    判断成功或者失败次数超出限制之后端开连接,返回结果。



    :param astr: 字符串命令
    :param host: 发送命令的server ip。 默认是给CSserver发送,
    :param port: server port。 默认是CSserver 的port。

    """
    time.sleep(0.2)
    # 1. 参数初始化
    bufsize = 1024
    addr = (host,port)

    # 1. 初始化socket
    client = socket(AF_INET, SOCK_STREAM)
    try:
        client.connect(addr)
    except error,e:
        write_logger('error', 'Connect  CSSERVER ERROR ')
        return None
Beispiel #5
0
def  insertnewzone(alist):
    """新插入一个元素(list 操作)
    """
    listitems = gamezones()
    dbnum = alist['db']

    res = getresbynum(dbnum)
    if res:
        #res = res.replace("'",'').lstrip('[(').rstrip(')]').split(',')
        res = eval(res)[0]
    else :
        write_logger('error',"CSServer return Num error!!")
        sys.exit(100)

    dbvalue = res[2].strip()
    dbname = res[3].strip()
    alist = argvToAlist(dbnum,dbvalue,dbname)

    listitems.append(alist)
    astr = "update iswork=1 dbnum=" + str(dbnum)

    res = getres(astr,host=csip)

    write_xml_alist(sortitems(listitems))
    sys.exit()
Beispiel #6
0
def pro2():
    """网络日志发送程序
    """
    aurlres = URLRes()
    debug =True if log2enable == "True" else False
    if debug:
        while True:
            res =  g.message_recv.recv()
            if aurlres.run(res[0],res[1]):
                write_logger('error',"can't connect webserver",internal=False)
Beispiel #7
0
def main():
    """主函数

       用来进行数据处理和日志记录,以及命令行的debug模式
    """
    write_logger('info','NDServer is starting')
    server = ThreadedTCPServer(addr,Servers)
    try:
        server.serve_forever()
    except KeyboardInterrupt,e:
        write_logger('debug', 'You cancel it!!!!!')
Beispiel #8
0
def main():
    """主函数

       用来进行数据处理和日志记录,以及命令行的debug模式
    """
    write_logger('info', 'NDServer is starting')
    server = ThreadedTCPServer(addr, Servers)
    try:
        server.serve_forever()
    except KeyboardInterrupt, e:
        write_logger('debug', 'You cancel it!!!!!')
Beispiel #9
0
def kaixinqu(alist):
    """开新区程序的操作非常的简单,操作如下::

        1. 参数判断,必须是两个参数
        2. 是否为新区判断
        3. 开区脚本执行

    需要注意的是::

        1. 参数中第一个为 *dbnum* ,第二个为 *time* ,时间参数的格式必须为"20150101"(8位)


    """
    # 因为只有一个正确结果,所以只需要删除两边的'[('和')]'
    #res = getres("findbydb " + str(num)).lstrip('[(').rstrip(')]').split(',')
    # 20151126 追加: 可以使用eval函数进行处理

    if len(alist) != 2:
        write_logger('error',"len(cmd) error")
        return [False, "len(cmd) error!!"]
    num = int(alist[0])
    time = alist[1]
    if len(time) !=  8:
        write_logger('error',"len(time)(required: 8)  error")
        return [False,"Time error!!,len(time)(required: 8) error"]


    res = getresbynum(num)
    print res
    if res :
        res = eval(res)[0]
    else :
        write_logger('error',"CSServer return  None!!")
        return [False,"CSServer return Num error!!"]

    # tag 用来判断是否是新区
    print res
    tag = int(res[4])
    if tag != 0 :
        write_logger('error',"Not new zone")
        return [False,"Not new zone"]



    # 2, 进行开区文件copy,重新启动cgi
    command = "sh commands/shelltools/CreateNewZone.sh" + " " +  str(num) +" "+ time
    #command = "echo $PATH"
    subp = subprores(command)
    if not subp:
        write_logger('error',"sh: CreateNewZone.sh, ERROR occurred!!!")
        return [False,"sh: CreateNewZone.sh, ERROR occurred!!!"]

    return [True,"Execution OK"]
Beispiel #10
0
def createTable(conn, sql):
    """ 创建数据库
    """
    if sql.split():
        cu = getCursor(conn)
        write_logger('debug', 'EXEC SQL: %s' % sql)
        cu.execute(sql)
        conn.commit()
        write_logger('INFO', 'EXEC SQL: %s' % sql)
        closeAll(conn, cu)
    else:
        print("The [{0}] is empty or equal None !".format(sql))
Beispiel #11
0
def pro2():
    """网络日志发送程序
    """
    aurlres = URLRes()
    debug = True if log2enable == "True" else False
    if debug:
        while True:
            res = g.message_recv.recv()
            if aurlres.run(res[0], res[1]):
                write_logger('error',
                             "can't connect webserver",
                             internal=False)
Beispiel #12
0
def createTable(conn,sql):
    """ 创建数据库
    """
    if sql.split() :
        cu = getCursor(conn)
        write_logger('debug','EXEC SQL: %s' % sql)
        cu.execute(sql)
        conn.commit()
        write_logger('INFO','EXEC SQL: %s' % sql)
        closeAll(conn,cu)
    else:
        print("The [{0}] is empty or equal None !".format(sql))
Beispiel #13
0
def tarfile(alist):
    """压缩文件
    """
    print alist
    command = "sh commands/shelltools/tarfile.sh"
    subp = subprores(command)
    if not subp:
        write_logger('error', 'changeZoneConf delete error ..............')
        return [False, "changeZoneConf delete ERROR occurred!!!"]
    write_logger('debug', 'changeZoneConf delete  EXE OK!!!!!!!!!!')

    return [True, "Execution OK"]
Beispiel #14
0
def  write_xml_alist(alist):
    """写入文件中
    """
    if gameversion == '10':
        print "10"
        writexmlbyxml(alist)
    elif gameversion == '5':
        print "5"
        writexmlbytext(alist)
    else:
        write_logger('error','Please Check your gameversion :  %s  in your config.cnf' % gameversion )
        sys.exit(100)
Beispiel #15
0
def tarfile(alist):
    """压缩文件
    """
    print alist
    command = "sh commands/shelltools/tarfile.sh"
    subp = subprores(command)
    if not  subp:
        write_logger('error','changeZoneConf delete error ..............')
        return [False,"changeZoneConf delete ERROR occurred!!!"]
    write_logger('debug','changeZoneConf delete  EXE OK!!!!!!!!!!')


    return [True,"Execution OK"]
Beispiel #16
0
def delete(conn, sql, data):
    if sql.split():
        if data is not None:
            cu = getCursor(conn)
            d = (data, )
            write_logger('DEBUG', 'EXEC SQL: %s' % sql)
            cu.execute(sql, d)
            conn.commit()
            closeAll(conn, cu)
            return [True, "DELETE OK"]
    else:
        write_logger('error', '%s is empty or equal None' % sql)
        return [False, "DELETE SQL ERROR"]
Beispiel #17
0
def delete(conn,sql,data):
    if sql.split():
        if data is not None:
            cu = getCursor(conn)
            d = (data,)
            write_logger('DEBUG','EXEC SQL: %s' % sql)
            cu.execute(sql,d)
            conn.commit()
            closeAll(conn,cu)
            return [True,"DELETE OK"]
    else:
        write_logger('error','%s is empty or equal None' % sql)
        return [False,"DELETE SQL ERROR"]
Beispiel #18
0
def kaixinqu(alist):
    """开新区程序的操作非常的简单,操作如下::

        1. 参数判断,必须是两个参数
        2. 是否为新区判断
        3. 开区脚本执行

    需要注意的是::

        1. 参数中第一个为 *dbnum* ,第二个为 *time* ,时间参数的格式必须为"20150101"(8位)


    """
    # 因为只有一个正确结果,所以只需要删除两边的'[('和')]'
    #res = getres("findbydb " + str(num)).lstrip('[(').rstrip(')]').split(',')
    # 20151126 追加: 可以使用eval函数进行处理

    if len(alist) != 2:
        write_logger('error', "len(cmd) error")
        return [False, "len(cmd) error!!"]
    num = int(alist[0])
    time = alist[1]
    if len(time) != 8:
        write_logger('error', "len(time)(required: 8)  error")
        return [False, "Time error!!,len(time)(required: 8) error"]

    res = getresbynum(num)
    print res
    if res:
        res = eval(res)[0]
    else:
        write_logger('error', "CSServer return  None!!")
        return [False, "CSServer return Num error!!"]

    # tag 用来判断是否是新区
    print res
    tag = int(res[4])
    if tag != 0:
        write_logger('error', "Not new zone")
        return [False, "Not new zone"]

    # 2, 进行开区文件copy,重新启动cgi
    command = "sh commands/shelltools/CreateNewZone.sh" + " " + str(
        num) + " " + time
    #command = "echo $PATH"
    subp = subprores(command)
    if not subp:
        write_logger('error', "sh: CreateNewZone.sh, ERROR occurred!!!")
        return [False, "sh: CreateNewZone.sh, ERROR occurred!!!"]

    return [True, "Execution OK"]
Beispiel #19
0
def dropTable(conn,table):
    """如果表存在,就删除表,如果表中存在数据,使用该方法的要注意
    """
    if table is not None and table != '':
        sql = 'DROP TABLE IF EXISTS' + TABLE
        write_logger('debug','EXEC SQL: %s \n\t\t AND ARGV: %s' % (sql,TABLE))
        cu = getCursor(conn)
        cu.execute(sql)
        conn.commit()
        write_logger('INFO','DELETE TABLE %s SUCESS' % TABLE )
        closeAll(conn,cu)
    else:
        
        print('the [{0}] is empty or equal None'.format(sql))
Beispiel #20
0
def save(conn, sql, data):
    """保存数据
    """
    if sql.split():
        if data is not None:
            cu = getCursor(conn)
            for d in data:
                write_logger('debug','EXEC SQL: %s  ' % sql)
                cu.execute(sql, d)
                conn.commit()
            closeAll(conn,cu)
        return [True,data]
    else:
        print('the [{0}] is emptry or equal None!'.format(sql))
        return [False, "SQL error"]
Beispiel #21
0
def save(conn, sql, data):
    """保存数据
    """
    if sql.split():
        if data is not None:
            cu = getCursor(conn)
            for d in data:
                write_logger('debug', 'EXEC SQL: %s  ' % sql)
                cu.execute(sql, d)
                conn.commit()
            closeAll(conn, cu)
        return [True, data]
    else:
        print('the [{0}] is emptry or equal None!'.format(sql))
        return [False, "SQL error"]
Beispiel #22
0
def dropTable(conn, table):
    """如果表存在,就删除表,如果表中存在数据,使用该方法的要注意
    """
    if table is not None and table != '':
        sql = 'DROP TABLE IF EXISTS' + TABLE
        write_logger('debug',
                     'EXEC SQL: %s \n\t\t AND ARGV: %s' % (sql, TABLE))
        cu = getCursor(conn)
        cu.execute(sql)
        conn.commit()
        write_logger('INFO', 'DELETE TABLE %s SUCESS' % TABLE)
        closeAll(conn, cu)
    else:

        print('the [{0}] is empty or equal None'.format(sql))
Beispiel #23
0
def deletezone(alist):
    """ 在domai_config删除alist元素。
    """
    listitems = gamezones()
    dbnum = alist['db']
    for line in listitems:
        if dbnum == line['db']:
            listitems.remove(line)
            astr = "update iswork=0 dbnum=" + str(dbnum)
            res = getres(astr, host=csip)
            write_xml_alist(listitems)
            sys.exit()

    write_logger('error', 'NO dbnum %s deleted' % str(dbnum))
    sys.exit()
Beispiel #24
0
def write_xml_alist(alist):
    """写入文件中
    """
    if gameversion == '10':
        print "10"
        writexmlbyxml(alist)
    elif gameversion == '5':
        print "5"
        writexmlbytext(alist)
    else:
        write_logger(
            'error',
            'Please Check your gameversion :  %s  in your config.cnf' %
            gameversion)
        sys.exit(100)
Beispiel #25
0
def update(conn,sql,data):
    """更新数据
    """
    if sql.split():
        if data is not None:
            cu = getCursor(conn)
            for d in data:
                cu.execute(sql,d)
                conn.commit()

            closeAll(conn,cu)
            return [True,"UPDATE SUCESS"]
    else:
        write_logger('error','%s is empty or equal None' % sql)
        return [False,"UPDATE error"]
Beispiel #26
0
def  deletezone(alist):
    """ 在domai_config删除alist元素。
    """
    listitems = gamezones()
    dbnum = alist['db']
    for line in listitems:
        if dbnum == line['db'] :
            listitems.remove(line)
            astr = "update iswork=0 dbnum=" + str(dbnum)
            res = getres(astr,host=csip)
            write_xml_alist(listitems)
            sys.exit()

    write_logger('error','NO dbnum %s deleted' % str(dbnum))
    sys.exit()
Beispiel #27
0
def update(conn, sql, data):
    """更新数据
    """
    if sql.split():
        if data is not None:
            cu = getCursor(conn)
            for d in data:
                cu.execute(sql, d)
                conn.commit()

            closeAll(conn, cu)
            return [True, "UPDATE SUCESS"]
    else:
        write_logger('error', '%s is empty or equal None' % sql)
        return [False, "UPDATE error"]
Beispiel #28
0
def getres(astr,host=csip,port=csport):
    """处理并返回结果

    Arguments:
    - `client,sys.argv`:
    """
    time.sleep(0.1)
    # 1. 参数初始化
    bufsize = 1024
    addr = (host,port)

    # 1. 初始化socket
    client = socket(AF_INET, SOCK_STREAM)
    try:
        client.connect(addr)
    except error,e:
        write_logger('error', 'Connect  CSSERVER ERROR ')
        return None
Beispiel #29
0
def getres(astr, host=csip, port=csport):
    """处理并返回结果

    Arguments:
    - `client,sys.argv`:
    """
    time.sleep(0.1)
    # 1. 参数初始化
    bufsize = 1024
    addr = (host, port)

    # 1. 初始化socket
    client = socket(AF_INET, SOCK_STREAM)
    try:
        client.connect(addr)
    except error, e:
        write_logger('error', 'Connect  CSSERVER ERROR ')
        return None
Beispiel #30
0
def writexmlbytext(alist):
    global filetopath
    domaiversion = getversion()

    ###################
    domai_xml_lines = []
    domai_xml_lines.append(r'<?xml version="1.0" encoding="UTF-8" ?>')
    domai_xml_lines.append('\n')
    domai_xml_lines.append(r'<configs>')
    domai_xml_lines.append('\n')
    domai_xml_lines.append(
        '\t' + r'<config name="server_path" value="/data/release/sgonline" />')
    domai_xml_lines.append('\n')
    domai_xml_lines.append('\t' + r'<config name="sversion" value="' +
                           str(domaiversion) + r'" />')
    domai_xml_lines.append('\n')
    #############

    if len(alist) > 0:
        dbnum = int(alist[0]['db'])
        res = getresbynum(dbnum)
        if res:
            res = eval(res)[0]
        else:
            write_logger('error', "CSServer return Num error!!")
            sys.exit(100)

        ip = res[1].strip()
        domai_xml_lines.append('\t' + r'<config name="' + str(ip) +
                               r'" value="' + str(alist[0]['value']) +
                               r'" db="' + str(alist[0]['db']) + '" />')
        domai_xml_lines.append('\n')

    for line in alist:
        domai_xml_lines.append('\t' + r'<config name="' + str(line['name']) +
                               r'" value="' + str(line['value']) + r'" db="' +
                               str(line['db']) + '" />')
        domai_xml_lines.append('\n')
    domai_xml_lines.append(r'</configs>')
    domai_xml_lines.append('\n')

    fp = open(filetopath, 'w')
    fp.writelines(domai_xml_lines)
    fp.close()
Beispiel #31
0
def writexmlbyxml(alist):
    """根据alist生成xml,然后让函数  **write_xml** 写入。
    """
    global filetopath
    domaiversion = getversion()
    root = ET.fromstring("<configs> </configs>")
    add_child_subelement(
        root,
        create_element("config", {
            'name': 'server_path',
            'value': '/data/release/sgonline'
        }, ''))
    add_child_subelement(
        root,
        create_element("config", {
            'name': 'sversion',
            'value': domaiversion
        }, ''))

    if len(alist) > 0:
        dbnum = int(alist[0]['db'])
        res = getresbynum(dbnum)
        if res:
            #res = res.replace("'",'').lstrip('[(').rstrip(')]').split(',')
            res = eval(res)[0]
        else:
            write_logger('error', "CSServer return Num error!!")
            sys.exit(100)

        ip = res[1].strip()

        add_child_subelement(
            root,
            create_element("config", {
                'name': ip,
                'db': alist[0]['db'],
                'value': alist[0]['value']
            }, ''))

    for line in alist:
        add_child_subelement(root, create_element("config", line, ''))
    indent(root)
    write_xml(ET.ElementTree(root), filetopath)
Beispiel #32
0
def arch_zone(alist):
    """根据合区的区号进行归档,得到ip-numlist 的对应关系,生成字典。
    """
    adict = {}
    for dbnum in alist:
        res = getresbynum(dbnum)
        if res :
            #res = res.replace("'",'').lstrip('[(').rstrip(')]').split(',')
            res = eval(res)[0]
        else :
            write_logger('error',"CSServer return  None!!")
            return [False,"CSServer return Num error!!"]

        ip =  res[1].strip()
        if ip in adict.keys():
            adict[ip] = adict[ip] + [dbnum,]
        else:
            adict[ip] = [dbnum,]

    return  adict
Beispiel #33
0
def changeZoneTime(alist):
    """更改区服时间的操作非常的简单,操作如下::

        1. 参数判断,必须是两个参数
        2. 是否为老区判断(未做)
        3. 更改时间脚本执行

    需要注意的是::

        1. 参数中第一个为 *dbnum* ,第二个为 *time* ,时间参数的格式必须为"20150101"(8位)


    """
    if len(alist) != 2:
        write_logger('error', "len(cmd) error")
        return [False, "len(cmd) error!!"]
    num = int(alist[0])
    time = alist[1]
    if len(time) != 8:
        write_logger('error', "len(time)(required: 8)  error")
        return [False, "Time error!!,len(time)(required: 8) error"]

    # 1, 进行开区文件copy,重新启动cgi
    command = "sh commands/shelltools/changeZoneTime.sh" + " " + str(
        num) + " " + time
    #command = "echo $PATH"
    subp = subprores(command)
    if not subp:
        write_logger('error', "sh: changeZoneTime.sh, ERROR occurred!!!")
        return [False, "sh: changeZoneTime.sh, ERROR occurred!!!"]

    return [True, "Execution OK"]
Beispiel #34
0
def fetchone(conn,sql,data):
    """查找,只返回一条结果
    """
    if sql.split():
        alist = []
        if data is not None:
            # Do this instead
            d = (data,)
            cu = getCursor(conn)
            write_logger('debug','EXEC SQL: %s \n\t\t AND ARGV: %s' % (sql,data))
            cu.execute(sql,d)
            r = cu.fetchall()
            res = []
            if len(r) > 0:
                for atuple in r :
                    j = ()
                    for i in atuple:
                        j += (str(i),)
                    res.append(j)
                        
                return [True,res]
        else:
            write_logger('ERROR','the command error!!')
    else:
        write_logger('ERROR','the sql is wrong!!')

    return [False,"sql error"]
Beispiel #35
0
def changeZoneTime(alist):
    """更改区服时间的操作非常的简单,操作如下::

        1. 参数判断,必须是两个参数
        2. 是否为老区判断(未做)
        3. 更改时间脚本执行

    需要注意的是::

        1. 参数中第一个为 *dbnum* ,第二个为 *time* ,时间参数的格式必须为"20150101"(8位)


    """
    if len(alist) != 2:
        write_logger('error',"len(cmd) error")
        return [False, "len(cmd) error!!"]
    num = int(alist[0])
    time = alist[1]
    if len(time) !=  8:
        write_logger('error',"len(time)(required: 8)  error")
        return [False,"Time error!!,len(time)(required: 8) error"]


    # 1, 进行开区文件copy,重新启动cgi
    command = "sh commands/shelltools/changeZoneTime.sh" + " " +  str(num) +" "+ time
    #command = "echo $PATH"
    subp = subprores(command)
    if not subp:
        write_logger('error',"sh: changeZoneTime.sh, ERROR occurred!!!")
        return [False,"sh: changeZoneTime.sh, ERROR occurred!!!"]

    return [True,"Execution OK"]
Beispiel #36
0
def fetchone(conn, sql, data):
    """查找,只返回一条结果
    """
    if sql.split():
        alist = []
        if data is not None:
            # Do this instead
            d = (data, )
            cu = getCursor(conn)
            write_logger('debug',
                         'EXEC SQL: %s \n\t\t AND ARGV: %s' % (sql, data))
            cu.execute(sql, d)
            r = cu.fetchall()
            res = []
            if len(r) > 0:
                for atuple in r:
                    j = ()
                    for i in atuple:
                        j += (str(i), )
                    res.append(j)

                return [True, res]
        else:
            write_logger('ERROR', 'the command error!!')
    else:
        write_logger('ERROR', 'the sql is wrong!!')

    return [False, "sql error"]
Beispiel #37
0
def writexmlbytext(alist):
    global filetopath
    domaiversion = getversion()

    ###################
    domai_xml_lines=[]
    domai_xml_lines.append(r'<?xml version="1.0" encoding="UTF-8" ?>')
    domai_xml_lines.append('\n')
    domai_xml_lines.append(r'<configs>')
    domai_xml_lines.append('\n')
    domai_xml_lines.append('\t' + r'<config name="server_path" value="/data/release/sgonline" />')
    domai_xml_lines.append('\n')
    domai_xml_lines.append('\t' + r'<config name="sversion" value="' + str(domaiversion)+r'" />')
    domai_xml_lines.append('\n')
    #############

    if len(alist) > 0:
        dbnum = int(alist[0]['db'])
        res = getresbynum(dbnum)
        if res :
            res = eval(res)[0]
        else :
            write_logger('error',"CSServer return Num error!!")
            sys.exit(100)

        ip = res[1].strip()
        domai_xml_lines.append('\t' + r'<config name="' + str(ip) + r'" value="' + str(alist[0]['value']) + r'" db="'+ str(alist[0]['db'])+'" />')
        domai_xml_lines.append('\n')

    for line in alist:
        domai_xml_lines.append('\t' + r'<config name="' + str(line['name']) + r'" value="' + str(line['value']) + r'" db="'+ str(line['db']) + '" />')
        domai_xml_lines.append('\n')
    domai_xml_lines.append(r'</configs>')
    domai_xml_lines.append('\n')

    fp = open(filetopath,'w')
    fp.writelines(domai_xml_lines)
    fp.close()
Beispiel #38
0
def main():
    """主函数

       用来进行数据处理和日志记录,以及命令行的debug模式
    """
    if not check():
        sys.exit(100)
    write_logger('info','CSServer  Check OK')
    write_logger('info','CSServer starts')
    server = ThreadedTCPServer(addr,Servers)
    try:
        server.serve_forever()
    except KeyboardInterrupt,e:
        write_logger('debug', 'You cancel it!!!!!')
Beispiel #39
0
def mvzone(alist):
    """ 迁区的核心程序。和 **合区** 相比只是少了合区的操作。还有就是第三步有差别
    目前涉及的几个步骤如下::

        1. 获取ip,numlist 并进行归档。
        2. 根据判断ip是否为本地进行分类操作

             * ip为本地ip,停服。
             * ip不是本机ip,则向该ip发送 **tarzone** 命令

        3. CSserver的数据库更改。主要是更改 *ip* 和 *value*
        4. 由于打包过来的文件日志目录缺失,增加日志目录
        5. 本地domai.conf配置增加。在 *第二步* 的时候将在domai.conf中本地的要合区的dbnum进行了删除。

    需要注意的是::
        1. *ip* 并不是必须存在的,如果存在合区到 *ip* 所在服务器上,如果不存在则合区到第一个 *dbnum* 所在的服务器上。

    """
    localip,dbnumlist = getIpAndDBnum(alist)
    zonedict = arch_zone(dbnumlist)
    print zonedict


    exittag = False
    for ip in zonedict.keys():
        if localip != ip :
            astr = "tarzone " + " ".join([str(x) for x in zonedict[ip]])
            write_logger('info', "sh: %s Ok" % astr)
            getres(astr,host=ip, port=1012)
            # 下载解压区服
            command = "sh commands/shelltools/scp.sh  " +  ip
            subp = subprores(command)
            if not subp:
                write_logger('error',"%s ERROR" % command)
                exittag = True
                return [False,"%s  ERROR occurred!!!" % command ]
            write_logger('info',"%s EXE  OK" % command)
        else:
            # 设置iswork=0,并重启cgi
            astr = " ".join([str(x) for  x in zonedict[ip]])
            command = "sh commands/shelltools/changeZoneConf.sh  delete " + astr
            subp = subprores(command)
            if not subp:
                write_logger('error',"%s ERROR" % command)
                exittag = True
                return [False,"changeZoneConf.sh  delete ERROR occurred!!!"]
            write_logger('info',"%s EXE  OK" % command)

    if exittag == True :
        return [False, "Error happened"]
    # 更改所有dbnum的ip为合区ip
    changezoneipandvalue(dbnumlist,localip)
    write_logger('info', "func: changezoneipandvalue happened!!!!"
    )

    # 创建日志文件
    astr = " ".join([str(x) for x in dbnumlist])

    write_logger('debug','createZoneLog.sh start.....................')
    command = "sh commands/shelltools/createZoneLog.sh " + astr
    subp = subprores(command)
    if not subp:
        write_logger('error',"sh: %s ERROR occurred!!!" % command)
        return [False,"createZoneLog.sh  ERROR occurred!!!"]
    write_logger('debug','createZoneLog.sh EXE Ok!!!!!!!!!!!!!')

    # 更改所有区的iswork=1,重启cgi ,over
    write_logger('debug',"changeZoneConf.sh add starting...............")
    command = "sh commands/shelltools/changeZoneConf.sh  add " + astr
    subp = subprores(command)
    if not subp:
        write_logger('error' "sh %s Error occurred!!!" % command)
        return [False,"changeZoneConf.sh add ERROR occurred!!!"]
    write_logger('debug',"changeZoneConf.sh add EXE OK!!!!!!!!!!!!!!!!!!")

    return [True, "hequ OK!!!!"]
Beispiel #40
0
    client = socket(AF_INET, SOCK_STREAM)
    try:
        client.connect(addr)
    except error,e:
        write_logger('error', 'Connect  CSSERVER ERROR ')
        return None
    # 这个print 必须存在,因为清空recv缓存
    client.recv(bufsize).strip()

    # check password 不能写在函数外部,需要动态动态生成
    password = getmd5()
    client.sendall('%s \n' % password)
    data = client.recv(bufsize)
    if data.find('OK') < 0:
        client.close()
        write_logger('error', "passsword check error")
        return None

    # 2. data 验证
    #data = sys.argv[1:]
    data = astr
    if not data or data == 'exit':
        write_logger('error', "the str you input is wrong")
        client.close()
        return None

    # 3. data 发送和接收
    client.sendall('%s \n'%data)

    data = ''
    # 增加哨兵进行就错判断
Beispiel #41
0
    def handle(self):
        """request 请求的处理函数。并作出response。也是我们处理的核心模块
           它经过了如下几个步骤::
             1. 验证密钥是否正确
             2. 函数交给dataanalyse函数进行处理
             3. 请求回应,并校验
             4. 判断回应是否成功
        """
        try:
            msg = 'got connection from ', self.client_address
            write_logger('info',msg)
            self.wfile.write('connection %s:%s at %s  succeed!\n'%(host,port,time.ctime()))

            while True:
                amd5 =  self.rfile.readline().strip()
                amd5str = getmd5()
                write_logger('debug',amd5str)

                if amd5 != amd5str:
                    self.wfile.write('refused!\n')
                    write_logger('debug','CSserver md5 : %s' % amd5str)
                    write_logger('debug', 'Client CSserver: %s'% amd5)
                    write_logger('error',"PassWord refused")
                    break


                self.wfile.write('check OK!\n')
                write_logger('info',"PassWord check OK!")

                ares=''
                while True:
                    res = ''
                    data = self.rfile.readline().strip()
                    if data != "retry" :
                        if data:
                            write_logger('info', "receive command: %s " % str(data))
                            res = dataanalyse.dataanalyse(data)
                        if res:
                            if res[0]:
                                write_logger('info',"command EXEC OK")
                            else:
                                write_logger('error',"command EXEC FAILED")

                            res = res[1]
                            write_logger('debug',"send result: %s" % res)
                        else:
                            res="None"

                    ares = str(len(str(res))) + "wshzaiyunwei" + str(res) + 'wshzaiyunweiend\n'

                    self.wfile.write(ares)
                    self.wfile.flush()

        except IOError, e:
            if e.errno == 32:
                print "IOError, you can ignore it! -----wsh"
Beispiel #42
0
    def handle(self):
        """request 请求的处理函数。并作出response。也是我们处理的核心模块
           它经过了如下几个步骤::
             1. 验证密钥是否正确
             2. 函数交给dataanalyse函数进行处理
             3. 请求回应,并校验
             4. 判断回应是否成功
        """
        try:
            msg = 'got connection from ', self.client_address
            write_logger('info', msg)
            self.wfile.write('connection %s:%s at %s  succeed!\n' %
                             (host, port, time.ctime()))

            while True:
                amd5 = self.rfile.readline().strip()
                amd5str = getmd5()
                write_logger('debug', amd5str)

                if amd5 != amd5str:
                    self.wfile.write('refused!\n')
                    write_logger('debug', 'CSserver md5 : %s' % amd5str)
                    write_logger('debug', 'Client CSserver: %s' % amd5)
                    write_logger('error', "PassWord refused")
                    break

                self.wfile.write('check OK!\n')
                write_logger('info', "PassWord check OK!")

                ares = ''
                while True:
                    res = ''
                    data = self.rfile.readline().strip()
                    if data != "retry":
                        if data:
                            write_logger('info',
                                         "receive command: %s " % str(data))
                            res = dataanalyse.dataanalyse(data)
                        if res:
                            if res[0]:
                                write_logger('info', "command EXEC OK")
                            else:
                                write_logger('error', "command EXEC FAILED")

                            res = res[1]
                            write_logger('debug', "send result: %s" % res)
                        else:
                            res = "None"

                    ares = str(len(str(res))) + "wshzaiyunwei" + str(
                        res) + 'wshzaiyunweiend\n'

                    self.wfile.write(ares)
                    self.wfile.flush()

        except IOError, e:
            if e.errno == 32:
                print "IOError, you can ignore it! -----wsh"
Beispiel #43
0
def mvzone(alist):
    """ 迁区的核心程序。和 **合区** 相比只是少了合区的操作。还有就是第三步有差别
    目前涉及的几个步骤如下::

        1. 获取ip,numlist 并进行归档。
        2. 根据判断ip是否为本地进行分类操作

             * ip为本地ip,停服。
             * ip不是本机ip,则向该ip发送 **tarzone** 命令

        3. CSserver的数据库更改。主要是更改 *ip* 和 *value*
        4. 由于打包过来的文件日志目录缺失,增加日志目录
        5. 本地domai.conf配置增加。在 *第二步* 的时候将在domai.conf中本地的要合区的dbnum进行了删除。

    需要注意的是::
        1. *ip* 并不是必须存在的,如果存在合区到 *ip* 所在服务器上,如果不存在则合区到第一个 *dbnum* 所在的服务器上。

    """
    localip, dbnumlist = getIpAndDBnum(alist)
    zonedict = arch_zone(dbnumlist)
    print zonedict

    exittag = False
    for ip in zonedict.keys():
        if localip != ip:
            astr = "tarzone " + " ".join([str(x) for x in zonedict[ip]])
            write_logger('info', "sh: %s Ok" % astr)
            getres(astr, host=ip, port=1012)
            # 下载解压区服
            command = "sh commands/shelltools/scp.sh  " + ip
            subp = subprores(command)
            if not subp:
                write_logger('error', "%s ERROR" % command)
                exittag = True
                return [False, "%s  ERROR occurred!!!" % command]
            write_logger('info', "%s EXE  OK" % command)
        else:
            # 设置iswork=0,并重启cgi
            astr = " ".join([str(x) for x in zonedict[ip]])
            command = "sh commands/shelltools/changeZoneConf.sh  delete " + astr
            subp = subprores(command)
            if not subp:
                write_logger('error', "%s ERROR" % command)
                exittag = True
                return [False, "changeZoneConf.sh  delete ERROR occurred!!!"]
            write_logger('info', "%s EXE  OK" % command)

    if exittag == True:
        return [False, "Error happened"]
    # 更改所有dbnum的ip为合区ip
    changezoneipandvalue(dbnumlist, localip)
    write_logger('info', "func: changezoneipandvalue happened!!!!")

    # 创建日志文件
    astr = " ".join([str(x) for x in dbnumlist])

    write_logger('debug', 'createZoneLog.sh start.....................')
    command = "sh commands/shelltools/createZoneLog.sh " + astr
    subp = subprores(command)
    if not subp:
        write_logger('error', "sh: %s ERROR occurred!!!" % command)
        return [False, "createZoneLog.sh  ERROR occurred!!!"]
    write_logger('debug', 'createZoneLog.sh EXE Ok!!!!!!!!!!!!!')

    # 更改所有区的iswork=1,重启cgi ,over
    write_logger('debug', "changeZoneConf.sh add starting...............")
    command = "sh commands/shelltools/changeZoneConf.sh  add " + astr
    subp = subprores(command)
    if not subp:
        write_logger('error' "sh %s Error occurred!!!" % command)
        return [False, "changeZoneConf.sh add ERROR occurred!!!"]
    write_logger('debug', "changeZoneConf.sh add EXE OK!!!!!!!!!!!!!!!!!!")

    return [True, "hequ OK!!!!"]
Beispiel #44
0
def hequ(alist):
    """ 合区的核心程序。
    目前涉及的几个步骤如下::

        1. 获取ip,numlist 并进行归档。
        2. 根据判断ip是否为本地进行分类操作

             * ip为本地ip,停服。
             * ip不是本机ip,则向该ip发送 **tarzone** 命令

        3. CSserver的数据库更改。主要是更改 *ip* 和 *value*
        4. 由于打包过来的文件日志目录缺失,增加日志目录
        5. 合区脚本执行
        6. 本地domai.conf配置增加。在 *第二步* 的时候将在domai.conf中本地的要合区的dbnum进行了删除。

    需要注意的是::
        1. *ip* 并不是必须存在的,如果存在合区到 *ip* 所在服务器上,如果不存在则合区到第一个 *dbnum* 所在的服务器上。

    """
    localip,dbnumlist = getIpAndDBnum(alist)

    for dbnum in dbnumlist:
        res = getresbynum(dbnum)
        print res
        if res :
            #res = res.replace("'",'').lstrip('[(').rstrip(')]').split(',')
            res = eval(res)[0]
        else :
            write_logger('error',"CSServer return  None!!")
            return [False,"CSServer return Num error!!"]

        # tag 用来判断是否是新区
        print res
        tag = int(res[4])
        if tag != 1 :
            write_logger('error',"Not old zone, can't hequ")
            return [False,"Not old zone . can't hequ"]

    zonedict = arch_zone(dbnumlist)
    print zonedict


    exittag = False
    for ip in zonedict.keys():
        if localip != ip :
            astr = "tarzone " + " ".join([str(x) for x in zonedict[ip]])
            write_logger('info', "sh: %s Ok" % astr)
            getres(astr,host=ip, port=1012)
            # 下载解压区服
            command = "sh commands/shelltools/scp.sh  " +  ip
            subp = subprores(command)
            if not subp:
                write_logger('error',"%s ERROR" % command)
                exittag = True
                return [False,"%s  ERROR occurred!!!" % command ]
            write_logger('info',"%s EXE  OK" % command)
        else:
            # 设置iswork=0,并重启cgi
            astr = " ".join([str(x) for  x in zonedict[ip]])
            command = "sh commands/shelltools/changeZoneConf.sh  delete " + astr
            subp = subprores(command)
            if not subp:
                write_logger('error',"%s ERROR" % command)
                exittag = True
                return [False,"changeZoneConf.sh  delete ERROR occurred!!!"]
            write_logger('info',"%s EXE  OK" % command)

    if exittag == True :
        return [False, "Error happened"]
    # 更改所有dbnum的ip为合区ip
    changezoneipandvalue(dbnumlist,localip)
    write_logger('info', "func: changezoneipandvalue happened!!!!")

    # 创建日志文件
    astr = " ".join([str(x) for x in dbnumlist])

    write_logger('debug','createZoneLog.sh start.....................')
    command = "sh commands/shelltools/createZoneLog.sh " + astr
    subp = subprores(command)
    if not subp:
        write_logger('error',"sh: %s ERROR occurred!!!" % command)
        return [False,"createZoneLog.sh  ERROR occurred!!!"]
    write_logger('debug','createZoneLog.sh EXE Ok!!!!!!!!!!!!!')

    # 执行合区脚本
    write_logger('debug',"hequ.sh  start .............")
    command = "sh commands/shelltools/hequ.sh " + astr
    subp = subprores(command)
    if not subp:
        write_logger('error',"sh %s Error occurred!!!" % command)
        return [False,"hequ.sh ERROR occurred!!!"]
    write_logger('debug',"hequ.sh EXE OK!!!!!!!!!!!!!!!")

    # 更改所有区的iswork=1,重启cgi ,over
    write_logger('debug',"changeZoneConf.sh add starting...............")
    command = "sh commands/shelltools/changeZoneConf.sh  add " + astr
    subp = subprores(command)
    if not subp:
        write_logger('error',"sh %s Error occurred!!!" % command)
        return [False,"changeZoneConf.sh add ERROR occurred!!!"]
    write_logger('debug',"changeZoneConf.sh add EXE OK!!!!!!!!!!!!!!!!!!")

    return [True, "hequ OK!!!!"]
Beispiel #45
0
    client = socket(AF_INET, SOCK_STREAM)
    try:
        client.connect(addr)
    except error, e:
        write_logger('error', 'Connect  CSSERVER ERROR ')
        return None
    # 这个print 必须存在,因为清空recv缓存
    client.recv(bufsize).strip()

    # check password 不能写在函数外部,需要动态动态生成
    password = getmd5()
    client.sendall('%s \n' % password)
    data = client.recv(bufsize)
    if data.find('OK') < 0:
        client.close()
        write_logger('error', "passsword check error")
        return None

    # 2. data 验证
    #data = sys.argv[1:]
    data = astr
    if not data or data == 'exit':
        write_logger('error', "the str you input is wrong")
        client.close()
        return None

    # 3. data 发送和接收
    client.sendall('%s \n' % data)

    data = ''
    # 增加哨兵进行就错判断
Beispiel #46
0
def tarzone(alist):
    """本地存在的alist进行压缩。主要的操作步骤::

        1. 停止要压缩的区服服务。
        2. 压缩区服。


    """
    numstr = " ".join([str(x) for x in alist])

    # 1. 修改配置
    write_logger('debug','changeZoneConf delete starting..............')
    command = "sh commands/shelltools/changeZoneConf.sh  delete " + numstr
    subp = subprores(command)
    if not  subp:
        write_logger('error','changeZoneConf delete error ..............')
        return [False,"changeZoneConf delete ERROR occurred!!!"]
    write_logger('debug','changeZoneConf delete  EXE OK!!!!!!!!!!')

    # 2. 执行压缩命令
    write_logger('debug', 'tarzone.sh starting...............')
    command = "sh commands/shelltools/tarzone.sh  " + numstr
    subp = subprores(command)
    if not subp:
        write_logger('error','tarzone.sh   error ..............')
        return [False,"tarzone.sh  ERROR occurred!!!"]
    write_logger('debug','tarzone.sh EXE OK!!!!!!!!!!')

    return [True,"Execution OK"]
Beispiel #47
0
def tarzone(alist):
    """本地存在的alist进行压缩。主要的操作步骤::

        1. 停止要压缩的区服服务。
        2. 压缩区服。


    """
    numstr = " ".join([str(x) for x in alist])

    # 1. 修改配置
    write_logger('debug', 'changeZoneConf delete starting..............')
    command = "sh commands/shelltools/changeZoneConf.sh  delete " + numstr
    subp = subprores(command)
    if not subp:
        write_logger('error', 'changeZoneConf delete error ..............')
        return [False, "changeZoneConf delete ERROR occurred!!!"]
    write_logger('debug', 'changeZoneConf delete  EXE OK!!!!!!!!!!')

    # 2. 执行压缩命令
    write_logger('debug', 'tarzone.sh starting...............')
    command = "sh commands/shelltools/tarzone.sh  " + numstr
    subp = subprores(command)
    if not subp:
        write_logger('error', 'tarzone.sh   error ..............')
        return [False, "tarzone.sh  ERROR occurred!!!"]
    write_logger('debug', 'tarzone.sh EXE OK!!!!!!!!!!')

    return [True, "Execution OK"]
Beispiel #48
0
            if op == "--getlist":
                state = 5
                dbnum = 11111
                dbvalue = 11111
            if op == "--file":
                filepath = value
            if op == "--tofile":
                filetopath = value


    except getopt.GetoptError,e:
        print e
        sys.exit(100)

    if not str(dbnum).split() or not str(dbvalue).split() :
        write_logger('error',"Error, no dbnum or dbvalue input")
        print "Error, no dbnum or dbvalue input"
        sys.exit(100)
    else:
        if state == 1:
            insertnewzone(argvToAlist(dbnum,dbvalue))
        elif state == 2:
            deletezone(argvToAlist(dbnum,dbvalue))
        elif  state == 3:
            print "Change"
            changezone(argvToAlist(dbnum,dbvalue))
        elif state == 4:
            print "show!!!!!!!!!!!"
            root = read_xml(filepath).getroot()
            list_element(root)
        elif state == 5:
Beispiel #49
0
                dbvalue = 11111
            if op == "--getlist":
                state = 5
                dbnum = 11111
                dbvalue = 11111
            if op == "--file":
                filepath = value
            if op == "--tofile":
                filetopath = value

    except getopt.GetoptError, e:
        print e
        sys.exit(100)

    if not str(dbnum).split() or not str(dbvalue).split():
        write_logger('error', "Error, no dbnum or dbvalue input")
        print "Error, no dbnum or dbvalue input"
        sys.exit(100)
    else:
        if state == 1:
            insertnewzone(argvToAlist(dbnum, dbvalue))
        elif state == 2:
            deletezone(argvToAlist(dbnum, dbvalue))
        elif state == 3:
            print "Change"
            changezone(argvToAlist(dbnum, dbvalue))
        elif state == 4:
            print "show!!!!!!!!!!!"
            root = read_xml(filepath).getroot()
            list_element(root)
        elif state == 5: