这篇文章给大家分享的是有关python中云服务器集群计算节点客户机网卡状态管理的脚本示例的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
计算节点服务端代码,响应客户端http请求,完成对虚拟机网卡的状态管理.
#! /usr/bin/python from wsgiref.simple_server import make_server import json import os import signal import shlex import subprocess from eventlet.green import subprocess as green_subprocess from eventlet import greenthread reserved_ip = "10.38.88.10" # this service rejects any request except those from 10.38.88.10 reserved_http_method = "POST" listen_port = 9999 def create_process(cmd, root_helper=None, addl_env=None): if root_helper: cmd = shlex.split(root_helper) + cmd cmd = map(str, cmd) env = os.environ.copy() if addl_env: env.update(addl_env) obj = subprocess_popen(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) return obj, cmd def execute(cmd, root_helper=None, process_input=None, addl_env=None, check_exit_code=True, return_stderr=False): try: obj, cmd = create_process(cmd, root_helper=root_helper, addl_env=addl_env) _stdout, _stderr = (process_input and obj.communicate(process_input) or obj.communicate()) obj.stdin.close() m = ("\nCommand: %(cmd)s\nExit code: %(code)s\nStdout: %(stdout)r\n" "Stderr: %(stderr)r") % {'cmd': cmd, 'code': obj.returncode, 'stdout': _stdout, 'stderr': _stderr} if obj.returncode and check_exit_code: raise RuntimeError(m) finally: greenthread.sleep(0) return return_stderr and (_stdout, _stderr) or _stdout def _subprocess_setup(): signal.signal(signal.SIGPIPE, signal.SIG_DFL) def subprocess_popen(args, stdin=None, stdout=None, stderr=None, shell=False, env=None): return green_subprocess.Popen(args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr, preexec_fn=_subprocess_setup, close_fds=True, env=env) def app(environ, start_response): source_ip = environ['REMOTE_ADDR'] request_method = environ['REQUEST_METHOD'] if source_ip != reserved_ip : status = '400 Bad Request' # Not Allowed headers = [('Content-type', 'application/json')] # HTTP Headers start_response(status, headers) return ['{"msg":"Not Acceptable"}'] if request_method != reserved_http_method: status = '405 Method Not Allowed' # Not Allowed headers = [('Content-type', 'application/json')] # HTTP Headers start_response(status, headers) return ['{"msg":"Method Not Allowed"}'] request_body_size = int(environ.get('CONTENT_LENGTH', 0)) request_body = environ['wsgi.input'].read(request_body_size) request_body = json.loads(request_body) param_vmid = request_body['id'] param_status = request_body['status'] hex_id = str(hex(param_vmid))[2:] for i in xrange(8-len(hex_id)): hex_id = "%d%s"%(0,hex_id) instance_name = "instance-%s"%hex_id mgmt = "virsh domiflist %s"%instance_name cmd = mgmt.split() try: retv = execute(cmd,root_helper=None) except Exception as e: status = '400 Bad Request' # Not Allowed headers = [('Content-type', 'application/json')] # HTTP Headers start_response(status, headers) return ['{"msg":"VM Not Found"}'] result = [] for line in retv.split("\n"): if "br-wan" in line: result.append(line) domif = result[0].split()[0].strip() if "-" == domif: status = '200 OK' # Not Allowed headers = [('Content-type', 'application/json')] # HTTP Headers start_response(status, headers) return ['{"msg":"Success"}'] else: mgmt = "ip link set %s %s"%(domif,param_status) cmd = mgmt.split() retv = execute(cmd,root_helper=None) status = '200 OK' # Not Allowed headers = [('Content-type', 'application/json')] # HTTP Headers start_response(status, headers) return ['{"msg":"Success"}'] httpd = make_server('', listen_port, app) httpd.serve_forever()
前台程序计算出客户机所处计算节点(宿主)ip,然后调用http请求,实现功能.
def kvm_conn_mgmt(self,instance_name,conn_status): if conn_status!='up' and conn_status!='down': return (resultcode.BadRequest, {"msg":"Vps conn status must be up/down"}) if len(instance_name.strip())==0: return (resultcode.BadRequest, {"msg":"Vps name should not be empty. "}) sql= "select i.id,cn.host_ip from instances as i,compute_nodes as cn where i.display_name='%s' and i.deleted=0 and i.host=cn.hypervisor_hostname"%instance_name result = db.execNovaSQL(sql) if len(result) == 0: return (resultcode.BadRequest, {"msg":"Vps with name '%s' does Not Exist. "%instance_name}) comp_host = result[0][1] vmid = result[0][0] msg = {"status":conn_status,"id":vmid} f = urllib.urlopen("http://%s:9999"%comp_host,json.dumps(msg)) content = f.read() if "Success" in content: return (resultcode.Success, {"msg":"Success"}) else: return (resultcode.BadRequest, {"msg":content})
计算节点运行服务监听端口9999,并限制只允许来自10.38.88.10的调用
iptables -A INPUT -p tcp -s 10.38.88.10 --dport 9999 -j ACCEPT
感谢各位的阅读!关于“python中云服务器集群计算节点客户机网卡状态管理的脚本示例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。