蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

本章实际实现与条件:chapter_suite.py

PYTHONWindows / Python3.12 / Temurin Java1.8.0_492 / ApacheZooKeeper3.9.7 / Curator5.9.0chapter_suite.py
chapter_suite.py47 行
from pathlib import Path
import os,json,time,uuid,re,subprocess
from lab_support import Lab,four_word,FOUR_WORDS
ACTIONS={'zookeeper-setup':'setup','zookeeper-java-setup':'java','zookeeper-znode-data-model':'model','zookeeper-session':'session','zookeeper-bs-command':'crud','zookeeper-node-feature':'features','zookeeper-acl':'acl','zookeeper-watcher':'watch','zookeeper-data-sync':'broadcast','zookeeper-locks':'locks'}
def probe(lab,nodes,action,path,value='unused'):
 r=subprocess.run(lab.command('MbskyProbe',action,lab.connect(nodes),path,value),capture_output=True,text=True,encoding='utf8',errors='replace',timeout=15);payload=[line.removeprefix('MBSKY_RESULT ')for line in r.stdout.splitlines()if line.startswith('MBSKY_RESULT ')];assert r.returncode==0 and len(payload)==1,(r.stdout,r.stderr);value=json.loads(payload[0]);assert value['passed'];return value
def expiration(lab,nodes):
 path='/mbsky_probe_'+uuid.uuid4().hex;err=(lab.run/'abrupt-owner.log').open('wb');owner=subprocess.Popen(lab.command('MbskyProbe','owner',lab.connect(nodes),path,'unused'),stdout=subprocess.PIPE,stderr=err,text=True,encoding='utf8');lab.processes.append(owner)
 try:
  line=owner.stdout.readline();assert line.startswith('MBSKY_READY '),line;ready=json.loads(line.removeprefix('MBSKY_READY '));owner.terminate();owner.wait(timeout=5);start=time.monotonic();first=probe(lab,nodes,'exists',path);assert first['exists']and first['ephemeral'],first
  last=first
  while last['exists']and time.monotonic()-start<12:time.sleep(.15);last=probe(lab,nodes,'exists',path)
  assert not last['exists'];return {'passed':True,'negotiated_timeout_ms':ready['timeout'],'immediately_after_disconnect_exists':first['exists'],'expired_and_removed':not last['exists'],'actual_observation_elapsed_ms':round((time.monotonic()-start)*1000),'scope':'Own process abrupt loss then actual server expiry, distinct from graceful close; not all network partitions'}
 finally:
  if owner.poll()is None:owner.terminate();owner.wait(timeout=5)
  err.close()
def leader_recovery(lab,nodes):
 modes=lab.wait_roles(nodes,True);before=modes.index('leader');path='/mbsky_probe_'+uuid.uuid4().hex;put=probe(lab,nodes,'put',path,'before-failover');committed=probe(lab,nodes,'get',path);leader=nodes[before];leader['process'].terminate();leader['process'].wait(timeout=5);survivors=[n for n in nodes if n is not leader];roles=lab.wait_roles(survivors,True);new_leader=next(n['id']for n,role in zip(survivors,roles)if role=='leader');assert new_leader!=leader['id'];read=probe(lab,survivors,'get',path);assert read['value']=='before-failover'and read['mzxid']==committed['mzxid'];probe(lab,survivors,'put',path,'after-failover')
 log=(lab.run/'restarted-leader.log').open('wb');lab.logs.append(log);proc=subprocess.Popen(lab.command('org.apache.zookeeper.server.quorum.QuorumPeerMain',leader['config']),stdout=log,stderr=log,cwd=Path(leader['config']).parent,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt'else 0);lab.processes.append(proc);leader['process']=proc;final_roles=lab.wait_roles(nodes,True);values=[probe(lab,[n],'get',path)for n in nodes];assert all(v['value']=='after-failover'for v in values);probe(lab,nodes,'delete',path)
 # This independent ordering model clarifies priorities, without claiming an implementation trace of every election packet.
 candidates=[(1,999,3),(2,1,1),(2,1,2)];winner=max(candidates);assert winner==(2,1,2)
 return {'passed':True,'original_leader_id':leader['id'],'replacement_leader_id':new_leader,'roles_after_restart':final_roles,'committed_data_retained':True,'actual_replica_values':[v['value']for v in values],'same_final_zxid':len({v['mzxid']for v in values})==1,'separate_priority_model_winner':winner,'scope':'Actual own3JVM election/recovery and committed-data reads; no claim of physical3machine resilience or exhaustive ZAB crash-point proof'}
def four_letters(lab,nodes):
 rows=[]
 for command in FOUR_WORDS:
  body=four_word(nodes[0]['port'],command);assert body.strip()or command in {'reqs','wchc','wchp','cons'},command
  if command=='ruok':assert body.strip()=='imok'
  if command=='srvr':assert'Mode: standalone'in body
  if command=='mntr':assert'zk_version'in body
  if command=='conf':assert'clientPort'in body
  rows.append({'command':command,'response_nonempty':bool(body.strip()),'empty_valid_when_no_matching_entries':command in {'reqs','wchc','wchp','cons'}and not body.strip(),'bytes':len(body.encode()),'sha256':__import__('hashlib').sha256(body.encode()).hexdigest(),'scope':'Actual own configured loopback server; raw environment details retained only private'if command=='envi'else'Actual own configured server'})
 denied=four_word(nodes[0]['port'],'stmk');assert'not'in denied and'whitelist'in denied;return {'passed':True,'commands':rows,'unlisted_command_rejected':True,'ruok_does_not_prove_quorum':True}
def cli_commands(lab,nodes):
 path='/mbsky_cli_'+uuid.uuid4().hex;commands=['create '+path+' MBSKY','ls -s '+path,'get -s '+path,'set -s -v 0 '+path+' mbsky.com','get -s '+path,'delete -v 1 '+path];result=lab.cli(nodes,commands);assert result['exit_code']==0,(result['stdout'],result['stderr']);assert'MBSKY'in result['stdout']and'mbsky.com'in result['stdout']and'cZxid'in result['stdout']and'dataVersion = 1'in result['stdout'],result;return {'passed':True,**result,'scope':'Actual modernCLI flags; historical ls2/rmr kept as migration knowledge, not false current commands'}
def run_chapter(key):
 lab=Lab(os.environ.get('MBSKY_ZK_RUN_DIR'));cluster=key in {'zookeeper-linux-cluster','zookeeper-data-sync','zookeeper-leader'}
 try:
  nodes=lab.start(cluster);cases=[]
  if key in ACTIONS:cases.append(lab.java_case(ACTIONS[key],nodes))
  if key=='zookeeper-linux-cluster':cases.append({'passed':True,'actual_roles':lab.wait_roles(nodes,True),'voters':3,'localhost_JVMs_not_three_machines':True})
  if key=='zookeeper-session':cases.append(expiration(lab,nodes))
  if key=='zookeeper-bs-command':cases.append(cli_commands(lab,nodes))
  if key=='zookeeper-sc-4lw':cases.append(four_letters(lab,nodes))
  if key=='zookeeper-leader':cases.append(leader_recovery(lab,nodes))
  assert cases;result={'chapter':key,'passed':True,'cases':cases,'compile':lab.compile,'server_config_sha256':{str(n['id']):__import__('hashlib').sha256(Path(n['config']).read_bytes()).hexdigest()for n in nodes},'server_count':len(nodes),'source_scripts_executed':False,'full_semantic_acceptance':False};print(json.dumps(result,ensure_ascii=False))
 finally:lab.close()
本例需在 Windows / Python3.12 / Temurin Java1.8.0_492 / ApacheZooKeeper3.9.7 / Curator5.9.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows / Python3.12 / Temurin Java1.8.0_492 / ApacheZooKeeper3.9.7 / Curator5.9.0

入口文件:projects/zk-lab/chapter_suite.py

预期结果与验证条件观察提示
  • 当前实现参与编译/运行的明确分支见本章实际记录,不把其它分支自动验收

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:ZooKeeper

课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202611a550.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习