Python 基于Python及zookeeper实现简单分布式任务调度系统设计思路及核心代码实现 2

本文涉及的产品
注册配置 MSE Nacos/ZooKeeper,182元/月
MSE Nacos/ZooKeeper 企业版试用,1600元额度,限量50份
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: Python 基于Python及zookeeper实现简单分布式任务调度系统设计思路及核心代码实现


appClient.py

 

#!/usr/bin/env python

#-*- encoding:utf-8 -*-

 

__author__ = 'shouke'

 

import time

from log import logger

 

from kazoo.client import  KazooClient

from kazoo.client import KazooState

 

def my_listener(state):

   if state == KazooState.LOST:

       logger.info('LOST')

 

       # Register somewhere that the session was lost

   elif state == KazooState.SUSPENDED:

       logger.info('SUSPENDED')

       # Handle being disconnected from Zookeeper

   else:

       logger.info('CONNECTED')

       # Handle being connected/reconnected to Zookeeper

 

def my_event_listener(event):

   logger.info(event)

 

 

zk_client = KazooClient(hosts='10.118.52.26:2181')

zk_client.add_listener(my_listener)

zk_client.start()

 

node_path = '/rootNode'

sub_node = 'loaderAgent102027165'

children = zk_client.get_children(node_path, watch=my_event_listener)

logger.info('there are %s children with names %s' % (len(children), children))

 

 

@zk_client.ChildrenWatch(node_path)

def watch_children(children):

   logger.info("Children are now: %s" % children)

 

 

@zk_client.DataWatch("%s/%s" % (node_path, sub_node))

def watch_node(data, state):

   """监视节点数据是否变化"""

   if state:

       logger.info('Version:%s, data:%s' % (state.version, data))

 

i = 0

while i < 1000:

   time.sleep(5)

   children = zk_client.get_children(node_path, watch=my_event_listener)

   logger.info('there are %s children with names %s' % (len(children), children))

   i += 1

 

zk_client.stop()

zk_client.close()

 

 

 

 

 

loadAgent.py

#!/usr/bin/env python 3.4.0

#-*- encoding:utf-8 -*-

 

__author__ = 'shouke'

 

import time

import threading

import configparser

import json

import subprocess

 

from kazoo.client import  KazooClient

from kazoo.client import KazooState

from log import logger

 

from myTCPServer import MyTCPServer

 

# 全局变量

zk_conn_stat = 0 # zookeeper连接状态 1-LOST   2-SUSPENDED 3-CONNECTED/RECONNECTED

registry_status = 0 # 服务器节点在zookeeper的注册状态  0-未注册、正在注册, 1-已注册

 

def restart_zk_client():

   '''重启zookeeper会话'''

 

   global zk_client

   global zk_conn_stat

   try:

       zk_client.restart()

       registry_zookeeper()

   except Exception as e:

       logger.error('重启zookeeper客户端异常:%s' % e)

 

 

def zk_conn_listener(state):

   '''zookeeper连接状态监听器'''

 

   global zk_conn_stat

   global registry_status

   if state == KazooState.LOST:

       logger.warn('zookeeper connection lost')

       zk_conn_stat = 1

       registry_status = 0 # 重置是否完成注册

       # Register somewhere that the session was lost

 

       thread = threading.Thread(target=restart_zk_client)

       thread.start()

 

   elif state == KazooState.SUSPENDED:

       logger.warn('zookeeper connection dicconnected')

       zk_conn_stat = 2

       # Handle being disconnected from Zookeeper

   else:

       zk_conn_stat = 3

       logger.info('zookeeper connection cconnected/reconnected')

       # Handle being connected/reconnected to Zookeeper

 

def registry_zookeeper():

   '''注册节点信息到zookeeper'''

 

   global node_parent_path

   global host

   global port

   global zk_client

   global zk_conn_stat

   global registry_status

 

   try:

       while zk_conn_stat != 3: # 如果zookeeper客户端没连上zookeeper,则先不让注册

           continue

 

       logger.info('正在注册负载机到zookeeper...')

       zk_client.ensure_path(node_parent_path)

 

       loader_agent_info = '{"host":"%s", "port":%s, "status":"idle"}' % (host, port)

 

       if not zk_client.exists('%s/loaderAgent%s' % (node_parent_path, host.replace('.', ''))):

           zk_client.create('%s/loaderAgent%s' % (node_parent_path, host.replace('.', '')), loader_agent_info.encode('utf-8'), ephemeral=True, sequence=False)

 

       # children = zk_client.get_children(node_parent_path)

       # logger.info('there are %s children with names: %s' % (len(children), children))

       # for child in children:

       #     logger.info(child)

       #     data, stat = zk_client.get('%s/%s' % (node_parent_path, child))

       #     logger.info(data)

       registry_status = 1 # 完成注册

       logger.info('注册负载机到zookeeper成功')

       return True

   except Exception as e:

       logger.error('注册负载机到zookeeper失败:%s' % e)

       return False

 

 

def start_tcpserver(tcpserver):

   '''启动tcp服务器'''

 

   tcpserver.start()

 

 

def get_server_status(proc_name):

   '''通过给定进程名称获取服务器状态'''

 

   with subprocess.Popen('ps -e | grep "%s"' % proc_name, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True) as proc:

       try:

           outs, errs = proc.communicate(timeout=30)

           outs = outs.strip()

           if outs.find(proc_name) != -1:

               # logger.info('获取负载机状态成功 %s' % outs)

               server_status = 'busy'

           elif outs == '':

               # logger.info('获取负载机状态成功')

               server_status = 'idle'

           else:

               logger.error('获取负载机状态失败:%s' % errs)

               server_status = 'unknow'

       except Exception as e:

           proc.kill()

           logger.error('获取负载机状态失败:%s' % e)

           server_status = 'unknow'

   return server_status

 

 

def update_server_status(interval, proc_name):

   '''定时检测并更新服务器状态:根据进程名称是否存在来判断服务器状态,如果存在则表示服务器被占用,标记服务器状态为busy,否则标记服务器状态为 idle

   如果根据进程名,检查进程失败,则标记服务器状态为unknow'''

 

   global node_parent_path

   global host

   global port

 

   while True:

       second_for_localtime1 = time.mktime(time.localtime()) # UTC时间(秒)

 

       if zk_conn_stat != 3: # 如果zookeeper客户端还没连上zookeeper,则不让进行后续操作

           continue

 

       if registry_status != 1: # 如果zookeeper客户端已连上zookeeper,但是还没注册节点到zookeeper,则不让进行后续操作

           continue

 

       server_status = get_server_status(proc_name)

       loader_agent_info = '{"host":"%s", "port":%s, "status":"%s"}' % (host, port, server_status)

       '''

       这里为啥要加这个判断:zookeeper删除临时节点存在延迟,如果zookeeper客户端主动关闭后快速重启并注册节点信息 这个过程耗时比较短,可能注册完节点信息时,zookeeper

       还没来得及删除重启之前创建的临时节点,而本次创建的临时节点路径和重启前的一模一样,这样导致的结果是,zookeeper接下来的删除操作,会把重启后注册的节点也删除

      '''

       if zk_client.exists('%s/loaderAgent%s' % (node_parent_path, host.replace('.', ''))):

           zk_client.set('%s/loaderAgent%s' % (node_parent_path, host.replace('.', '')), loader_agent_info.encode('utf-8'))

       else:

           registry_zookeeper()

 

       second_for_localtime2 = time.mktime(time.localtime()) # UTC时间(秒)

       time_difference = second_for_localtime2 - second_for_localtime1

       if time_difference < interval:

           time.sleep(interval - time_difference)

 

 

if __name__ == '__main__':

   logger.info('正在启动代理...')

 

   try:

       logger.info('正在读取zookeeper配置...')

       config_parser = configparser.ConfigParser()

       config_parser.read('./conf/zookeeper.conf', encoding='utf-8-sig')

       zk_hosts = config_parser.get('ZOOKEEPER', 'hosts').replace(',', ',').strip()

       node_parent_path = config_parser.get('ZOOKEEPER', 'nodeParentPath').replace(',', ',').strip()

 

       logger.info('正在构建并启动zookeeper客户端...')

       zk_client = KazooClient(hosts=zk_hosts)

       zk_client.add_listener(zk_conn_listener)

       zk_client.start()

   except Exception as e:

       logger.error('初始化zookeeper客户端失败: %s' % e)

       exit(1)

 

   try:

       config_parser.clear()

       config_parser.read('./conf/tcpserver.conf', encoding='utf-8-sig')

       host = config_parser.get('TCPSERVER', 'host')

       port = int(config_parser.get('TCPSERVER', 'port'))

       tcp_server  = MyTCPServer(host, port)

       thread = threading.Thread(target=start_tcpserver, args=(tcp_server,))

       thread.start()

   except Exception as e:

       logger.error('TCPServer启动失败:%s,请检查配置/conf/tcpserver.conf是否正确' % e)

       exit(1)

 

 

   try:

       # 注册到zookeeper

       registry_zookeeper()

 

       config_parser.clear()

       config_parser.read('./conf/agent.conf', encoding='utf-8-sig')

       interval = int(config_parser.get('AGENT', 'interval'))

       proc = config_parser.get('AGENT', 'proc').strip()

 

       # 定时更新服务器节点繁忙状态

       update_server_status(interval, proc)

   except Exception as e:

       logger.error('zk_client运行失败:%s,请检查配置/conf/agent.conf是否正确' % e)

       exit(1)

 

 

 

运行效果

 

 

目录
相关文章
|
1月前
|
存储 算法 调度
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
143 26
|
21天前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
200 100
|
21天前
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
233 95
|
29天前
|
Python
Python的简洁之道:5个让代码更优雅的技巧
Python的简洁之道:5个让代码更优雅的技巧
188 104
|
29天前
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
334 99
|
21天前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
132 88
|
8天前
|
消息中间件 分布式计算 资源调度
《聊聊分布式》ZooKeeper与ZAB协议:分布式协调的核心引擎
ZooKeeper是一个开源的分布式协调服务,基于ZAB协议实现数据一致性,提供分布式锁、配置管理、领导者选举等核心功能,具有高可用、强一致和简单易用的特点,广泛应用于Kafka、Hadoop等大型分布式系统中。
|
27天前
|
监控 机器人 编译器
如何将python代码打包成exe文件---PyInstaller打包之神
PyInstaller可将Python程序打包为独立可执行文件,无需用户安装Python环境。它自动分析代码依赖,整合解释器、库及资源,支持一键生成exe,方便分发。使用pip安装后,通过简单命令即可完成打包,适合各类项目部署。
|
1月前
|
设计模式 人工智能 API
AI智能体开发实战:17种核心架构模式详解与Python代码实现
本文系统解析17种智能体架构设计模式,涵盖多智能体协作、思维树、反思优化与工具调用等核心范式,结合LangChain与LangGraph实现代码工作流,并通过真实案例验证效果,助力构建高效AI系统。
297 7
|
1月前
|
JSON 缓存 开发者
淘宝商品详情接口(item_get)企业级全解析:参数配置、签名机制与 Python 代码实战
本文详解淘宝开放平台taobao.item_get接口对接全流程,涵盖参数配置、MD5签名生成、Python企业级代码实现及高频问题排查,提供可落地的实战方案,助你高效稳定获取商品数据。

热门文章

最新文章

推荐镜像

更多