根据:
mapper.resource("loadbalancer", "loadbalancers",
member={'details': 'GET'},
controller=lb_resource, collection={'detail': 'GET'})
self._list()对应底层的index()函数
self._create()对应底层的create()函数
self._delete()对应底层的delete()函数
self._get()对应底层的show()函数
由上图对应关系我们可以知道create()函数的webservice发布为:
return self._create("/loadbalancers", body, "loadbalancer")
接着就自动调用balancer里面的:
@utils.http_success_code(202)
def create(self, req, body):
LOG.debug("Got create request. Request: %s", req)
#here we need to decide which device should be used
params = body.copy()#将参数复制
LOG.debug("Headers: %s", req.headers)
# We need to create LB object and return its id
tenant_id = req.headers.get('X-Tenant-Id', "")
params['tenant_id'] = tenant_id#参数列表中获取tenant_id
lb_id = core_api.create_lb(self.conf, params)
#跟进到1.1层
return {'loadbalancer': {'id': lb_id}}#返回一个包含lb_id的字典列表
2、第1.1层、
def create_lb(conf, params):
nodes = params.pop('nodes', [])#获取nodes参数列表,其详细内容,参考下面注解
probes = params.pop('healthMonitor', [])#获取监测检查的参数列表,其详细内容,参考下面注解
vips = params.pop('virtualIps', [])#获取虚拟VIP参数列表,其详细内容,参考下面注解
values = db_api.loadbalancer_pack_extra(params)#解析参数为一个字典列表
lb_ref = db_api.loadbalancer_create(conf, values)#更新loadbalancer的数据库,返回值为models.LoadBalancer()数据库表。
跟进到下一层1.1.1
device = scheduler.schedule_loadbalancer(conf, lb_ref)#根据当前lb数据,修改底层配置device文件,进行调度。
跟进到下一层1.1.2
device_driver = drivers.get_device_driver(conf, device['id'])#获取device驱动,
跟进到下一层1.1.3
lb = db_api.unpack_extra(lb_ref)#将lb_ref转变为一个字典
lb['device_id'] = device['id']
lb_ref = db_api.loadbalancer_pack_extra(lb)#加入device_id选项之后再次封装
try:
with device_driver.request_context() as ctx:#此处ctx的作用???(相关驱动配置???)
commands.create_loadbalancer(ctx, lb_ref, nodes, probes, vips)#创建loadbalancer,
跟进到下一层1.1.4
except (exception.Error, exception.Invalid):
lb_ref.status = lb_status.ERROR
lb_ref.deployed = 'False'
else:
lb_ref.status = lb_status.ACTIVE
lb_ref.deployed = 'True'
db_api.loadbalancer_update(conf, lb['id'], lb_ref)
return lb_ref['id']
注解:
nodes里面包括虚拟机的地址,以及端口和负载均衡调度的权重参数等。
healthMonitor里面包括???
VIP用来连接外部和内部实例IP直接通讯的中间层IP。这样当我们机器出现故障时,我们的VIP还能正常工作接受外部服务和请求。
3、第1.1.1层
更新models.LoadBalancer()数据库表值,返回整个LoadBalancer()表格数据
4、第1.1.2层
def schedule_loadbalancer(conf, lb_ref):
conf.register_opts(bind_opts)#绑定特定配置文件,以便于修改为特定配置文件
device_filters = [utils.import_class(foo) for foo in conf.device_filters]
all_devices = db_api.device_get_all(conf)#获取所有 models.Device数据库表 ,
跟进到下一层1.1.2.1
if not all_devices:#如果没有设备则报设备找不到异常
raise exp.DeviceNotFound
cost_functions = []
for fullname in conf.device_cost_functions:
conf_name = 'device_cost_%s_weight' % fullname.rpartition('.')[-1]
try:
weight = getattr(conf, conf_name)#获取权重
except cfg.NoSuchOptError:
conf.register_opt(cfg.FloatOpt(conf_name, default=1.))
weight = getattr(conf, conf_name)
cost_functions.append((utils.import_class(fullname), weight))
filtered_devices = [dev for dev in all_devices
if all(filt(conf, lb_ref, dev)
for filt in device_filters)]
if not filtered_devices:
raise exp.NoValidDevice
costed = []
for dev in filtered_devices:
w = 0.
for cost_func, weight in cost_functions:
w += weight * cost_func(conf, lb_ref, dev)
costed.append((w, dev))
costed.sort()
return costed[0][1]
5、第1.1.2.1层
获取models.Device数据库表里面的所有数据
6、第1.1.3层
7、第1.1.4层
def create_loadbalancer(ctx, balancer, nodes, probes, vips):
lb = db_api.unpack_extra(balancer)#解封装为字典
sf = db_api.serverfarm_create(ctx.conf, {'lb_id': lb['id']})#创建serverfarm(更新models.ServerFarm()数据库表),跟进下一层1.1.4.1
if 'algorithm' in lb:#如果lb参数中有’algorithm‘则获取type属性字典
predictor_params = {'sf_id': sf['id'], 'type': lb['algorithm']}
else:
predictor_params = {'sf_id': sf['id']}
db_api.predictor_create(ctx.conf, predictor_params)#更新数据到预报器models.Predictor()数据库表中
create_server_farm(ctx, sf)#创建serverfarm(更新models.ServerFarm()数据库表),跟进下一层1.1.4.2
for node in nodes:#如果参数中有node则更新server数据库
node_values = db_api.server_pack_extra(node)
node_values['sf_id'] = sf['id']#加入sf_id重新封装
rs_ref = db_api.server_create(ctx.conf, node_values)#更新models.Server()数据库数据
create_rserver(ctx, rs_ref)#创建rserver,更新models.Server()数据库数据
add_rserver_to_server_farm(ctx, sf, rs_ref)#跟进到下一层1.1.4.3
for probe in probes:#如果参数中有probe(探测器)则更新probe数据库
probe_values = db_api.probe_pack_extra(probe)
probe_values['lb_id'] = lb['id']
probe_values['sf_id'] = sf['id']
probe_ref = db_api.probe_create(ctx.conf, probe_values)#更新probe数据库
create_probe(ctx, probe_ref)# 代码pass:???
add_probe_to_server_farm(ctx, sf, probe_ref)
for vip in vips:#如果参数中有vip则更新virturalIps数据库
vip_values = db_api.virtualserver_pack_extra(vip)
vip_values['lb_id'] = lb['id']
vip_values['sf_id'] = sf['id']
vip_ref = db_api.virtualserver_create(ctx.conf, vip_values)
create_vip(ctx, vip_ref, sf)##跟进到下一层1.1.4.4
8、第1.1.4.1层
更新models.ServerFarm()数据库表
9、第1.1.4.2层
@with_rollback
def create_server_farm(ctx, sf):
try:
pr = db_api.predictor_get_all_by_sf_id(ctx.conf, sf['id'])#通过sf_id过滤获取models.Predictor数据
ctx.device.create_server_farm(sf, pr) #????
db_api.serverfarm_update(ctx.conf, sf['id'], {'deployed': True})#更新
serverfarm数据库表
yield
except Exception:
delete_server_farm(ctx, sf)#出现异常则删除刚刚建立好的数据库数据
raise
10、1.1.4.3层
@with_rollback
def add_rserver_to_server_farm(ctx, server_farm, rserver):
try:
if (rserver.get('parent_id') and rserver['parent_id'] != ""):
#Nasty hack. We need to think how todo this more elegant
rserver['name'] = rserver['parent_id']
ctx.device.add_real_server_to_server_farm(server_farm, rserver)#根据特定的device(以HAproxy为例),
跟进到下一层1.1.4.3.1层
yield
except Exception:
ctx.device.delete_real_server_from_server_farm(server_farm, rserver)
raise
11、第1.1.4.3.1层
def add_real_server_to_server_farm(self, serverfarm, rserver):
haproxy_serverfarm = HaproxyBackend()
haproxy_serverfarm.name = serverfarm['id']
haproxy_rserver = HaproxyRserver()
haproxy_rserver.name = rserver['id']
haproxy_rserver.weight = rserver.get('weight') or 1
haproxy_rserver.address = rserver['address']
haproxy_rserver.port = rserver.get('port') or 0
haproxy_rserver.maxconn = rserver['extra'].get('maxCon') or 10000
#Modify remote config file, check and restart remote haproxy
logger.debug('[HAPROXY] Creating rserver %s in the '
'backend block %s' %
(haproxy_rserver.name, haproxy_serverfarm.name))
config_file = self._get_config()#???
config_file.add_rserver_to_backend_block(haproxy_serverfarm,
haproxy_rserver)#???
12、第
1.1.4.4 层
def create_virtual_ip(self, virtualserver, serverfarm):
if not bool(virtualserver['id']):
logger.error('[HAPROXY] Virtualserver name is empty')
return 'VIRTUALSERVER NAME ERROR'
haproxy_virtualserver = HaproxyFronted()
haproxy_virtualserver.name = virtualserver['id']
haproxy_virtualserver.bind_address = virtualserver['address']
haproxy_virtualserver.bind_port = virtualserver.get('port') or 0
haproxy_serverfarm = HaproxyBackend()
haproxy_serverfarm.name = serverfarm['id']
logger.debug('[HAPROXY] create VIP %s' % haproxy_serverfarm.name)
#Add new IP address
remote_interface = RemoteInterface(self.device_ref,
haproxy_virtualserver)
remote_interface.add_ip()
#Modify remote config file, check and restart remote haproxy
config_file = self._get_config()
config_file.add_frontend(haproxy_virtualserver, haproxy_serverfarm)