首页 > 代码库 > Day3-HAproxy

Day3-HAproxy

HAproxy配置文件操作
1. 根据用户输入输出对应的backend下的server信息
2. 可添加backend 和sever信息
3. 可修改backend 和sever信息
4. 可删除backend 和sever信息
5. 操作配置文件前进行备份
6 添加server信息时,如果ip已经存在则修改;如果backend不存在则创建;若信息与已有信息重复则不操作

 

技术分享
  1 import json  2 import os  3   4   5 def show_all_backend(filename):  6     try:  7         l_backend = []  8         with open(filename, r, encoding=utf-8) as f:  9             lines = f.readlines() 10             for line in lines: 11                 if line.strip().startswith(backend): 12                     l_backend.append(line) 13         if l_backend: 14             for i,j in enumerate(l_backend): 15                 print (\t%s % (i + 1), j) 16             return True 17  18         else: 19             print(No actived backends!) 20             return False 21     except EOFError as msg: 22         print(msg) 23  24  25 def show_server_info_under_backend(url): 26     l_backend = [] 27     f = open(HAproxy, r, encoding=utf-8) 28     lines = f.readlines() 29     for i in range(len(lines)): 30         if lines[i].strip().startswith(backend): 31             item = lines[i].strip().strip(\n) 32             new_item = item.strip(backend ) 33             #print (new_item) 34             l_backend.append(new_item) 35     #print (l_backend) 36     if url in l_backend: 37         for i in range(len(lines)): 38             if lines[i].strip().startswith(backend %s%url): 39                 j = lines.index(lines[i]) 40                 #print (lines[j]) 41         i = j+1 42         l_base = [] 43         if url == l_backend[-1]: 44             p = lines.index(backend %s\n%l_backend[-1]) 45             for item in lines[p+1:]: 46                 l_base.append(item.strip().strip(\n)) 47         else: 48             while True: 49                 if lines[i].strip().startswith(server): 50                     l_base.append(lines[i].strip().strip(\n)) 51                     i +=1 52                     if (lines[i].strip().startswith(backend)): 53                         break 54  55         for i, j in enumerate(l_base): 56             print(\t%s % (i + 1), j) 57         return True 58     else: 59         return False 60  61 def is_backend_exists(url): 62     try: 63         lbackend = [] 64         f = open(HAproxy, r, encoding=utf-8) 65         lines = f.readlines() 66         for i in range(len(lines)): 67             if lines[i].startswith("backend"): 68                 lbackend.append(lines[i][len("backend "):].strip(\n)) 69         f.close() 70  71         if url in lbackend: 72             #print("backend %s exists!Please added server info directly"%url) 73             return True 74         else: 75             return False 76  77     except EOFError as msg: 78         print(msg) 79  80     finally: 81         f.close() 82  83 def add_backend(url): 84     try: 85         f = open(HAproxy, a+, encoding=utf-8) 86         if not is_backend_exists(url): 87             f.writelines("\n\rbackend %s" % url) 88             print("Add backend %s successfully" % url) 89         else: 90             print("Fail to add backend %s since it already exists" % url) 91  92     except EOFError as msg: 93         print(msg) 94  95     finally: 96         f.close() 97  98  99 def del_backend(url):100     try:101         if is_backend_exists(url):102             f = open(HAproxy, r+, encoding=utf-8)103             lines = f.readlines()104             f.close()105 106             if url in lines[-1].strip():107                 lines[-1]=""108             else:109                 for i in range(len(lines)):110                     if lines[i].startswith(backend) and (url in lines[i]):111                         lines[i] = ""112                         j = i + 1113                         while True:114                             if lines[-1].strip().startswith(server):115                                 break116                             elif lines[j].strip().startswith(server):117                                 lines[j] = ""118                                 j += 1119                             else:120                                 break121             f = open(HAproxy, w+, encoding=utf-8)122             f.writelines(lines)123             f.close()124             print(Delete backend %s sucessfully!%url)125             return True126         else:127             print(Delete Failed - No such backend sever exits)128             return False129 130     except EOFError as msg:131          print(msg)132 133 134 def show_all_active_server_info(filename):135     try:136         l_server = []137         with open(filename, r, encoding=utf-8) as f:138             lines = f.readlines()139             for line in lines:140                 if line.strip().startswith(server):141                     l_server.append(line)142         if l_server:143             str = "The active server info as below:"144             print(str.center(60,*))145             for i, j in enumerate(l_server):146                 print(\t%s % (i + 1), j)147             return True148 149         else:150             print(No actived servers!)151             return False152     except EOFError as msg:153         print(msg)154 155 def add_server_info_under_backend(str):156     # Tranfer inside str to dict157     try:158         dict = json.loads(str)159         # print (dict)160         item = "server {server} weight {weight} maxconn {maxconn}".format(**dict[record])161         #print(type(item))162         i = 0163         if is_backend_exists(dict[backend]):164             f = open(HAproxy, r+, encoding=utf-8)165             lines = f.readlines()166             f.close()167             #print (lines)168             l_backend = []169             for line in lines:170                 if dict[backend] in line.strip(\n):171                     index = lines.index(line)172                     i = index173                     # print(lines[i])174                     break175 176             for line in lines:177                 if line.strip().startswith(backend):178                     l_backend.append(line)179 180             if dict[backend] in l_backend[-1]:181                 l_set = []182                 for line in lines[i:]:183                     l_set.append(line.strip().strip(\n))184                 # print(l_set)185                 # print(item)186                 if item in l_set:187                     return False188 189                 else:190                     with open(HAproxy, r, encoding=utf-8) as f1:191                         lines = f1.readlines()192                     l_ip = []193                     #print(dict[‘record‘][‘server‘])194                     for n in range(len(lines)):195                         if lines[n].startswith(\t\tserver %s  % dict[record][server]):196                             l_ip.append(lines[n])197                     if l_ip:198                         dict = json.loads(str)199                         item2 = "server {server} weight {weight} maxconn {maxconn}".format(**dict[record])200                         with open(HAproxy, r+, encoding=utf-8) as f2:201                             new_lines = f2.readlines()202                             p = 0203                             for line in new_lines:204                                 if \t\tserver %s  % dict[record][server] in line:205                                     p = new_lines.index(line)206 207                             new_lines[p] = \t\t%s\n % item2208                         with open(HAproxy, w+, encoding=utf-8) as f3:209                             f3.writelines(new_lines)210                             print(Update server info successfully!)211                             return True212 213                     else:214                         f = open(HAproxy, a+, encoding=utf-8)215                         line = "\n\t\tserver {server} weight {weight} maxconn {maxconn}".format(**dict[record])216                         f.writelines(line)217                         f.close()218             else:219                 j=i+1220                 l_server = []221                 while True:222                     if lines[j].strip().startswith(server):223                         l_server.append(lines[j].strip().strip(\n))224                         j +=1225                         if lines[j].strip().startswith(backend):226                             break227                 if item in l_server:228                     return False229                 else:230                     with open(HAproxy, r, encoding=utf-8) as f1:231                         lines = f1.readlines()232                     l_ip = []233                     #print(dict[‘record‘][‘server‘])234                     for n in range(len(lines)):235                         if lines[n].startswith(\t\tserver %s %dict[record][server]):236                             l_ip.append(lines[n])237                     if l_ip:238                         dict = json.loads(str)239                         item2 = "server {server} weight {weight} maxconn {maxconn}".format(**dict[record])240                         with open(HAproxy, r+, encoding=utf-8) as f2:241                             new_lines = f2.readlines()242                             p = 0243                             for line in new_lines:244                                 if \t\tserver %s %dict[record][server] in line:245                                     p = new_lines.index(line)246 247                             new_lines[p] = \t\t%s\n%item2248                         with open(HAproxy, w+, encoding=utf-8) as f3:249                             f3.writelines(new_lines)250                             print(hello?)251                             return True252 253                     else:254                         lines.insert(j,"\t\tserver {server} weight {weight} maxconn {maxconn}\n".format(**dict[record]))255                         f = open(HAproxy, w+, encoding=utf-8)256                         f.writelines(lines)257                         f.close()258                     return True259 260         else:261             add_backend(dict[backend])262             print(dict[record])263             f = open(HAproxy, a+, encoding=utf-8)264             line = "\n\t\tserver {server} weight {weight} maxconn {maxconn}".format(**dict[record])265             f.writelines(line)266             f.close()267 268     except EOFError as msg:269         print(msg)270 271 def del_server_info_under_backend(str):272     try:273         f = open(HAproxy, r+, encoding=utf-8)274         lines = f.readlines()275         l_backend = []276         for line in lines:277             if line.strip().startswith(backend):278                 l_backend.append(line.strip())279         f.close()280 281         for i in range(len(lines)):282             if str in lines[i].strip():283                 print(Delete server info: %s % str)284                 p = lines.index(lines[i])285                 if (lines[p-1].strip().startswith(backend)) and (lines[p].strip() in lines[-1]):286                     lines.remove(lines[p])287                     # print(‘No actived server under %s, remove backend‘%lines[p-1].strip().strip(‘\n‘))288                     lines.remove(lines[p - 1])289                     break290                 elif (lines[p-1].strip().startswith(backend))and (lines[p+1].strip().startswith(backend)):291                     lines.remove(lines[p])292                     # print(‘No actived server under %s, remove backend!‘%lines[p - 1].strip().strip(‘\n‘))293                     lines.remove(lines[p - 1])294                     break295                 else:296                     lines.remove(lines[p])297                     break298         f = open(HAproxy, w+, encoding=utf-8)299         f.writelines(lines)300         return True301 302     except EOFError as msg:303         print(msg)304 305 306 def backup_server_file(original_file,new_file):307     try:308         with open(original_file,r,encoding=utf-8) as f1, open(new_file,w,encoding=utf-8) as f2:309             lines = f1.readlines()310             for line in lines:311                 f2.writelines(line)312         str = Backing up is Done!313         print(str.center(40,*))314     except EOFError as msg:315         print(msg)316 317 318 if __name__ == "__main__":319     counter = 0320     bValue =http://www.mamicode.com/ True321     while True:322         counter +=1323         if counter == 3:324             print(You`ve entered invalid info for 3 times, system quit!)325             exit()326 327         else:328 329             row_input = input("Do you want to operate server file?(y/n) ")330             if row_input in [n,N,q,Q]:331                 print(Quit)332                 exit()333             elif row_input in [y,Y]:334                 bValue =http://www.mamicode.com/ True335                 while True:336                     print(Backing up your server file as HAproxy_bak on your server..)337                     backup_server_file(HAproxy, HAproxy_bak)338                     # row_input = input("1.Show all backend  | 2.Add new backend | 3.Delete backend ")339                     if bool(show_all_backend(HAproxy)) == True:340                         while True:341                             str = The active backends as below:342                             print(str.center(60,*))343                             show_all_backend(HAproxy)344                             row_input = input(1.Add backend server info | 2.Delete backend | 3 View server info under backend | 4 Show all actived server info  )345                             if row_input in [q,Q]:346                                 print(Quit)347                                 exit()348                             elif row_input == "1":349                             #     row_input = input(‘Enter the backend url you want to add here -> : ‘)350                             #     if row_input in [‘q‘, ‘Q‘]:351                             #         print(‘Quit‘)352                             #     else:353                             #         add_backend(row_input)354                             #         continue355                                 print(You should add sever info like {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}})356                                 row_input = input(Enter your new server info here->: )357                                 if row_input in [q, Q]:358                                     print(Quit)359                                     exit()360                                 else:361                                     backup_server_file(HAproxy, HAproxy_bak)362                                     add_server_info_under_backend(row_input)363                                     continue364 365                             elif row_input == "2":366                                 row_input = input(Enter the backend url you want to delete here -> : )367                                 if row_input in [q, Q]:368                                     print(Quit)369                                     exit()370                                 else:371                                     backup_server_file(HAproxy, HAproxy_bak)372                                     del_backend(row_input)373                                     continue374 375                             elif row_input == "3":376                                 row_input = input(Enter the backend url under which you want to check server info here-> : )377                                 if row_input in [q, Q]:378                                     print(Quit)379                                 else:380                                     backup_server_file(HAproxy, HAproxy_bak)381                                     while True:382                                         if bool(show_server_info_under_backend(row_input)):383                                             row_input = input(1.Add or Update sever info | 2. Delete server info | 3. Return to the previous menu)384                                             if row_input in [q, Q]:385                                                 print(Quit)386                                                 exit()387                                             elif row_input == 1:388                                                 print(You should add sever info like {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}})389                                                 row_input = input(Enter your new server info here->: )390                                                 if row_input in [q, Q]:391                                                     print(Quit)392                                                     exit()393                                                 else:394                                                     backup_server_file(HAproxy, HAproxy_bak)395                                                     add_server_info_under_backend(row_input)396                                                     continue397                                             # elif row_input == ‘2‘:398                                             #     pass399 400                                             elif row_input == 2:401 402                                                 if row_input in [q, Q]:403                                                     print(Quit)404                                                     exit()405                                                 else:406 407                                                     if row_input in [q, Q]:408                                                         print(Quit)409                                                         exit()410 411                                                     else:412                                                         backup_server_file(HAproxy, HAproxy_bak)413                                                         row_input = input(Please enter your server info you want to delete here->)414                                                         del_server_info_under_backend(row_input)415                                                         continue416                                             elif row_input == 3:417                                                 continue418                                             else:419                                                 print(Invalid input choice, please re-enter)420                                                 continue421 422                                         else:423                                             break424 425 426                             elif  row_input == "4":427                                 if bool(show_all_active_server_info(HAproxy)) == True:428 429                                      #show_all_active_server_info(‘HAproxy‘)430                                      continue431                                 else:432                                     backup_server_file(HAproxy, HAproxy_bak)433                                     row_input = input(There is no actived server info exists, want to add? (y/n))434                                     if row_input in [q, Q]:435                                         print(Quit)436                                         exit()437                                     elif row_input in [y, Y]:438                                         print(You should add sever info like {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}})439                                         row_input = input(Enter your new server info here->: )440                                         if row_input in [q, Q]:441                                             print(Quit)442                                             exit()443                                         else:444                                             add_server_info_under_backend(row_input)445                                             continue446 447                             else:448                                 print(Not invalid choice, please re-enter again.)449                                 continue450 451                     else:452                         row_input = input(There is no actived server info exists, want to add? (y/n))453                         if row_input in [q, Q]:454                             print(Quit)455                             exit()456                         elif row_input in [y, Y]:457                             print(458                                 You should add sever info like {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}})459                             row_input = input(Enter your new server info here->: )460                             if row_input in [q, Q]:461                                 print(Quit)462                                 exit()463                             else:464                                 backup_server_file(HAproxy, HAproxy_bak)465                                 add_server_info_under_backend(row_input)466                                 continue467                         else:468                             continue469 470 471 472 473             else:474                 print(Not invalid choice , please re-enter again\n)475                 continue
View Code

技术分享

Day3-HAproxy