haproxy

Posted 伊川草

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了haproxy相关的知识,希望对你有一定的参考价值。

# Author rendelei

#_*_coding:utf-8_*_
import os

import datetime


def fetch(data):
# backend www.oldboy.org
# server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
backend_data ="backend %s" %data
record_list = []
with open("D:\python_project\storage\cap1\ha_config.txt",‘r‘) as f:
tag = False #设置标签
for line in f:
if line.strip() == backend_data: #判断如果匹配到backend,则就标签设置为True
tag =True
continue
if tag and line.startswith("backend"): #判断如果匹配到下一个以backend开始的字符串,则退出for循环。
break #由于tag为True,因此需要将判断匹配下一个backend放在添加record列表前面
if tag and line: #将backend匹配的下面的行添加到record_list的列表中
record_list.append(line.strip()) #line.strip()去掉line结果的空行
for line in record_list:
print(line)
print (record_list)
return record_list #将record_list列表的值返回给函数fetch(data)


def add(data):
#格式:dict {"backend":"www.oldboy5.org","record":{"server":"10.10.10.10","server":"10.10.10.10","weight":"20","maxconn":"300"}}
value = data[‘backend‘] # 取出key为backend的字典的value值
record_list = fetch(value) #value值作为查询函数的参数传给fetch(),并将函数的返回值赋值给record_list
#将backend下面行的内容通过字典的value值匹配,并赋值给current_record
current_record = "server %s %s weight %s maxconn %s" %(data[‘record‘][‘server‘],\
data[‘record‘][‘server‘],\
data[‘record‘][‘weight‘],\
data[‘record‘][‘maxconn‘])
backend_data = "backend %s" %value

if not record_list:
record_list.append(backend_data)
record_list.append(current_record)
with open ("D:\python_project\storage\cap1\ha_config.txt",‘r‘) as r_file, \
open("D:\python_project\storage\cap1\ha_config_new.txt", ‘w‘) as w_file:
for r_line in r_file: #将源文件写入新文件
w_file.write(r_line)
for new_line in record_list:
if new_line.startswith(‘backend‘):
w_file.write(new_line+‘\n‘)
else:
w_file.write("%s%s\n" % (‘ ‘*8,new_line))
else:
#即record_list不为空
# 在record_list中添加backend 信息,如果添加的backend信息已经存在,
record_list.insert(0,backend_data)
#将要添加的sever信息记录加到record_list中
if current_record not in record_list: #???如果添加的新的信息在record_list中,输出已经存在该信息,else怎么会出现问题,但是测试没问题?(格式问题,已解决)
record_list.append(current_record)
with open("D:\python_project\storage\cap1\ha_config.txt", ‘r‘) as r_file, \
open("D:\python_project\storage\cap1\ha_config_new.txt", ‘w‘) as w_file:
tag = False
# 由于在else模块中tag为True在读相应的server信息中,会每读一行,则写一次record_list中的信息
# 因此需要判断在读到新的backend信息之前只需写一次record_list信息即可
has_write = False
for r_line in r_file:
if r_line.strip() == backend_data:
tag = True
continue
if tag and r_line.startswith(‘backend‘):
tag = False
if not tag:
w_file.write(r_line)
else:
if not has_write:
for new_line in record_list:
if new_line.startswith(‘backend‘):
w_file.write(new_line + ‘\n‘)
else:
w_file.write("%s%s\n" % (‘ ‘ * 8, new_line))
has_write = True



# 更改文件名
os.rename("D:\python_project\storage\cap1\ha_config.txt",
"D:\python_project\storage\cap1\ha_config_bak.txt")
os.rename("D:\python_project\storage\cap1\ha_config_new.txt",
"D:\python_project\storage\cap1\ha_config.txt")
os.remove("D:\python_project\storage\cap1\ha_config_bak.txt")
else:
print("This record is already exist!")


def remove(data):
value = data[‘backend‘]
record_list = fetch(value)
current_record = "server %s %s weight %s maxconn %s" % (data[‘record‘][‘server‘], \
data[‘record‘][‘server‘], \
data[‘record‘][‘weight‘], \
data[‘record‘][‘maxconn‘])
backend_data = "backend %s" % value
if not record_list or current_record not in record_list:
print("\033[41;1mThere is no record of this!\033[0m")
return
else:
record_list.insert(0,backend_data)
record_list.remove(current_record)
with open("D:\python_project\storage\cap1\ha_config.txt", ‘r‘) as r_file, \
open("D:\python_project\storage\cap1\ha_config_new.txt", ‘w‘) as w_file:
tag = False
has_write = False
for r_line in r_file:
if r_line.strip() == backend_data:
tag =True
continue
if tag and r_line.startswith(‘backend‘):
tag = False
if not tag:
w_file.write(r_line)
else:
if not has_write:
for new_line in record_list:
if new_line.startswith(‘backend‘):
w_file.write(new_line + ‘\n‘)
else:
w_file.write("%s%s\n" % (‘ ‘ * 8, new_line))
has_write = True
os.rename("D:\python_project\storage\cap1\ha_config.txt", "D:\python_project\storage\cap1\ha_config_bak.txt")
os.rename("D:\python_project\storage\cap1\ha_config_new.txt", "D:\python_project\storage\cap1\ha_config.txt")
os.remove("D:\python_project\storage\cap1\ha_config_bak.txt")
def change(data):
# 格式:[{"backend":"www.oldboy5.org","record":{"server":"10.10.10.10","weight":"20","maxconn":"300"}},
# {"backend":"www.oldboy5.org","record":{"server":"18.18.18.18","weight":"200","maxconn":"3000"}}]
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 = "backend %s" %backend
if not record_list or old_record not in record_list: #为空或者要修改的内容信息与record_list不一致
print("\033[41;1mThere is no this record!\033[0m")
return
else:
record_list.insert(0,backend_data)
index= record_list.index(old_record)
record_list[index]= new_record
with open("D:\python_project\storage\cap1\ha_config.txt", ‘r‘) as r_file, \
open("D:\python_project\storage\cap1\ha_config_new.txt", ‘w‘) as w_file:
tag = False
has_write = False
for r_line in r_file:
if r_line.strip() == backend_data:
tag = True
continue
if tag and r_line.startswith(‘backend‘):
tag = False
if not tag:
w_file.write(r_line)
else:
if not has_write:
for new_line in record_list:
if new_line.startswith(‘backend‘):
w_file.write(new_line + ‘\n‘)
else:
w_file.write("%s%s\n" % (‘ ‘ * 8, new_line))
has_write = True


os.rename("D:\python_project\storage\cap1\ha_config.txt", "D:\python_project\storage\cap1\ha_config_bak.txt")
os.rename("D:\python_project\storage\cap1\ha_config_new.txt", "D:\python_project\storage\cap1\ha_config.txt")
os.remove("D:\python_project\storage\cap1\ha_config_bak.txt")

def backup(choice):
with open("D:\python_project\storage\cap1\ha_config.txt", ‘r‘) as r_file, \
open("D:\python_project\storage\cap1\ha_config_copy_%s.txt" \
% datetime.datetime.now().strftime("%Y_%m_%d"), ‘w‘) as w_file:
for r_line in r_file:
w_file.write(r_line)
print("you backup the file successful!")
if __name__ ==‘__main__‘:
mgs=‘‘‘
what woul you like to do with this HAproxy file?
1:fetch
2:add
3:delete
4:change
5:backup
6:exit
‘‘‘
menu_dict={
‘1‘:fetch,
‘2‘:add,
‘3‘:remove,
‘4‘:change,
‘5‘:backup,
‘6‘:exit
}
while True:
print(mgs) #先输出可选择功能项
choice = input("select>>>:").strip()
#判断input的输入,如果是不输入或者输入不为 menu_dict中的key值,则继续循环输入
if len(choice)== 0 or choice not in menu_dict:continue
if choice == ‘5‘:
backup(choice)
continue
if choice == ‘6‘:break
data = input("data>>>:").strip()
#判断input的输入,如果不是1,即add or remove ,由于输入格式为字典,则需要进行字典转化为字符串
if choice is not ‘1‘:
data = eval(data)
#利用字典的key值获取value值进而用作为函数,并将输入值作为参数传给函数
menu_dict[choice](data)

以上是关于haproxy的主要内容,如果未能解决你的问题,请参考以下文章

haproxy

HAProxy杂记

Haproxy-负载均衡

HAproxy配置

haproxy

HAProxy介绍