您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。