vars.py
3.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author tiexin.yang@yoho.cn
import os
import sys
import json
import argparse
import re
class vars_maker():
"""
作用: 一区二区之间进行双中心切换(一区切换至二区)前生成临时的参数文件,用于覆盖原有的DNS配置,最终生成临时文件/home/ansible/yoho-ansible-roles/inventories/.switch.yml
Demo:
demo = vars_maker()
demo.start()
"""
def __init__(self, az1_vars, az2_vars, az3_vars, zone1_tmp_yml, zone2_tmp_yml, zone3_tmp_yml):
self.az1_write_map = {}
self.az2_read_map = {}
self.tmp_dns_map = {}
self.az1_vars = az1_vars
self.az2_vars = az2_vars
self.az3_vars = az3_vars
self.zone1_tmp_yml = zone1_tmp_yml
self.zone2_tmp_yml = zone2_tmp_yml
self.zone3_tmp_yml = zone3_tmp_yml
self.target_dns = [
"db_cms_write",
"db_passport_write",
"db_shops_write",
"db_order_write",
"db_uic_write",
"db_ordersplit_1_write",
"db_ordersplit_2_write",
"db_ordersplit_3_write",
"db_ordersplit_4_write"
]
def splitVar(self,entry):
#将参数配置文件根据格式dns:ip分割成key,value形式
ip = entry.split(':')[-1].strip()
dns = entry.split(':')[0].strip().replace('_write','').replace('_read','')
return dns,ip
def load_vars(self):
#加载一区二区的yml参数文件并录入字典对象
for entry in self.az1_vars:
if 'write' in entry:
dns,ip = self.splitVar(entry)
self.az1_write_map[dns] = ip
for entry in self.az2_vars:
if 'read' in entry:
dns,ip = self.splitVar(entry)
self.az2_read_map[dns] = ip
print 'Write DNS:'
print json.dumps(self.az1_write_map,indent=4)
print 'Read DNS:'
print json.dumps(self.az2_read_map,indent=4)
return True
def update_tmp_vars(self,zoneNum=1):
#创建临时切换参数文件
if zoneNum == 1:
tmp_yml = self.zone1_tmp_yml
var_rows = self.az1_vars
elif zoneNum == 2:
tmp_yml = self.zone2_tmp_yml
var_rows = self.az2_vars
elif zoneNum == 3:
tmp_yml = self.zone3_tmp_yml
var_rows = self.az3_vars
else:
print 'Wrong zone number! Must be integer in value [1,2,3]!'
return False
with open(tmp_yml,'w') as f:
for row in var_rows:
write_matched = False
for write_dns in self.tmp_dns_map:
if write_dns in row and write_dns in self.target_dns:
new_dns_entry = '{0}: {1}\n'.format(write_dns,self.tmp_dns_map[write_dns])
f.write(new_dns_entry)
write_matched = True
break
if write_matched:
continue
else:
f.write(row+'\n')
return True
def start(self):
print '\033[1;32m生成临时DNS参数文件...\033[0m'
self.load_vars()
#在一区切换至二区时,一二三区的write dns应当全部解析到二区的read dns
for zone1_dns in self.az1_write_map.keys():
tmp_dns = '{0}_write'.format(zone1_dns)
tmp_ip = self.az2_read_map[zone1_dns]
self.tmp_dns_map[tmp_dns] = tmp_ip
print 'Write DNS after switch:'
print json.dumps(self.tmp_dns_map,indent=2)
for zoneNum in [1,2,3]:
self.update_tmp_vars(zoneNum)
return True