首页 > 代码库 > 修改Haproxy文件配置,实现增删改查

修改Haproxy文件配置,实现增删改查

Haproxy 源文件

global
        log 127.0.0.1 local2
        daemon
        maxconn 256
        log 127.0.0.1 local2 info
defaults
        log global
        mode http
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        option  dontlognull

listen stats :8888
        stats enable
        stats uri       /admin
        stats auth      admin:1234

frontend oldboy.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.oldboy.org
        use_backend www.oldboy.org if www

backend www.oldboy.org
        server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333
        server 10.10.10.1 10.10.10.1 weight 22 maxconn 2000
        server 2.2.2.4 2.2.2.4 weight 20 maxconn 3000

backend www.oldboy2.org
        server 3.3.3.3 3.3.3.3 weight 20 maxconn 3000

backend www.oldboy20.org
        server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333

作业要求

1 输入 www.oldboy.org 查询文件是否有记录节点的信息

2 输入一个字典,再在文件中添加一条backend 和server的记录

3 输入一个字典,删除文件中记录的文件

4 输入一个列表,列表中涵盖两个字典,第一个是源文件中的信息,第二个是要修改的字典样子

正文代码(没有把新的文件覆盖源文件,等到代码优化的时候再备份源文件和覆盖源文件)

__author__ = ‘shellxie‘
# -*- coding:utf-8 -*-
import os
def fetch(data):
    backend_data = "http://www.mamicode.com/backend %s"%data
    record_list =[]
    set_flag = False
    with open("haproxy.conf","r") as f:
        for line in f:
            if line.strip() == backend_data:
                set_flag = True
                continue
            if line.strip().startswith("backend"):
                break
            if set_flag and line :
                record_list.append(line.strip())
        for line in record_list:
            print(line.strip())
        return  record_list
def add(data):#用户输入的有两种可能,一个是输入的backend存在haproxy,一个是不存在haproxy,如果不存在我们就添加,如果存在,添加server或者不添加
    backend = data["backend"]
    record_list= fetch(backend)
    current_record = "server %s %s weight %s maxconn %s"%(data["record"]["server"],                                                          data["record"]["server"],                                                          data["record"]["weight"],                                                          data["record"]["maxconn"],)
    backend_data ="http://www.mamicode.com/backend %s"%backend

    if not record_list:#列表为空说明用户输入的不存在haproxy,那么执行以下添加代码操作
        record_list.append(backend_data)
        record_list.append(current_record)
        with open("haproxy.conf","r") as read_file,            open("haproxy_new.conf","w") as write_file:
            for line in read_file:
                write_file.write(line)
            for new_line in record_list:
                if new_line.startswith("backend"):
                    write_file.write("\n"+new_line+"\n")
                else:
                    write_file.write("%s%s"%(" "*8,new_line))
    else:
        #print(record_list)
        record_list.insert(0,backend_data)
        if current_record not in record_list:
            record_list.append(current_record)
            with open("haproxy.conf","r") as read_file,                open("haproxy_new.conf","w") as write_file:
                tag =False
                has_write= False
                for r_line in read_file:
                    if r_line.strip() == backend_data:
                        tag =True
                        continue
                    if tag and r_line.strip().startswith("backend"):
                        tag =False
                    if not tag:
                        write_file.write(r_line)

                    else:
                        if not has_write:
                            for new_line in record_list:
                                if new_line.startswith("backend"):
                                    write_file.write(new_line+"\n")
                                else:
                                    write_file.write("%s%s"%(" "*8,new_line+"\n"))
                            has_write =True

def remove(data):# 删除和添加其实是一样的,都是三个步骤,第一步骤源文件读到要删除的那个backend, 第二步骤把要删除的那个backend和server记录 放在一个列表中,读完到新文件中,第三读完剩余的文件
    backend = data["backend"]#第一步骤要判断用户输入的是否在源文件中,还是要通过查询功能来实现
    backend_data = "http://www.mamicode.com/backend %s"%backend
    record_list = fetch(backend)
    current_record = "server %s %s weight %s maxconn %s"%(data["record"]["server"],                                                          data["record"]["server"],                                                          data["record"]["weight"],                                                          data["record"]["maxconn"],)
    if not record_list or current_record not in record_list:
        print("\033[33;1m无此条记录\033[0m")
        return
    else:# 如果用户输入的字典里面backend 值是存在的,但是server 记录不存在,那是不是也删除不了,所以这里同样要提示
        record_list.insert(0,backend_data)
        record_list.remove(current_record)
        with open("haproxy.conf","r") as read_file,                open("haproxy_new.conf","w") as write_file:
                tag =False
                has_write= False
                for r_line in read_file:
                    if r_line.strip() == backend_data:
                        tag =True
                        continue
                    if tag and r_line.strip().startswith("backend"):
                        tag =False
                    if not tag:
                        write_file.write(r_line)

                    else:
                        if not has_write:
                            for new_line in record_list:
                                if new_line.startswith("backend"):
                                    write_file.write("\n"+new_line+"\n")
                                else:
                                    write_file.write("%s%s"%(" "*8,new_line+"\n"))
                            has_write =True


def revise(data):
    backend = data[0]["backend"]
    record_list =fetch(backend)
    old_record ="server %s %s weight %s maxconn %s"%(data[0]["record"]["server"],                                                    data[0]["record"]["server"],                                                    data[0]["record"]["weight"],                                                    data[0]["record"]["maxconn"],)
    new_record ="server %s %s weight %s maxconn %s"%(data[1]["record"]["server"],                                                    data[1]["record"]["server"],                                                    data[1]["record"]["weight"],                                                    data[1]["record"]["maxconn"],)
    backend_data ="http://www.mamicode.com/backend %s"%backend
    print(backend)
    print(backend_data)
    if not record_list or old_record not in record_list:
        print("\033[33;1m无此记录\033[0m")
        return
    else:
        record_list.insert(0,backend_data)
        index = record_list.index(old_record)
        record_list[index]= new_record
        with open("haproxy.conf","r") as read_file,                open("haproxy_new.conf","w") as write_file:
                tag =False
                has_write= False
                for r_line in read_file:
                    if r_line.strip() == backend_data:
                        tag =True
                        continue
                    if tag and r_line.strip().startswith("backend"):
                        tag =False
                    if not tag:
                        write_file.write(r_line)

                    else:
                        if not has_write:
                            for new_line in record_list:
                                if new_line.startswith("backend"):
                                    write_file.write(new_line+"\n")
                                else:
                                    write_file.write("%s%s"%(" "*8,new_line+"\n"))
                            has_write =True
if __name__ == "__main__":
    msg = """
        1:查询
        2:添加
        3:删除
        4:修改
        5:退出
    """
    menu_dic ={
        "1":fetch,
        "2":add,
        "3":remove,
        "4":revise,
        "5":exit
    }
    while True:
        print(msg)
        choice = input("选择功能>>:").strip()
        if len(choice) == 0 or choice not in menu_dic:
            continue
        if choice == "5":break
        data = http://www.mamicode.com/input("用户想要输入的数据:").strip()
        if choice !="1":
            data =http://www.mamicode.com/eval(data)>

  

修改Haproxy文件配置,实现增删改查