溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python中云服務(wù)器集群計(jì)算節(jié)點(diǎn)客戶機(jī)網(wǎng)卡狀態(tài)管理的腳本示例

發(fā)布時(shí)間:2021-11-08 10:11:11 來源:億速云 閱讀:133 作者:小新 欄目:云計(jì)算

這篇文章給大家分享的是有關(guān)python中云服務(wù)器集群計(jì)算節(jié)點(diǎn)客戶機(jī)網(wǎng)卡狀態(tài)管理的腳本示例的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

計(jì)算節(jié)點(diǎn)服務(wù)端代碼,響應(yīng)客戶端http請(qǐng)求,完成對(duì)虛擬機(jī)網(wǎng)卡的狀態(tài)管理.

#! /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()

前臺(tái)程序計(jì)算出客戶機(jī)所處計(jì)算節(jié)點(diǎn)(宿主)ip,然后調(diào)用http請(qǐng)求,實(shí)現(xiàn)功能.

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})

計(jì)算節(jié)點(diǎn)運(yùn)行服務(wù)監(jiān)聽端口9999,并限制只允許來自10.38.88.10的調(diào)用

iptables -A INPUT -p tcp -s 10.38.88.10 --dport 9999 -j ACCEPT

感謝各位的閱讀!關(guān)于“python中云服務(wù)器集群計(jì)算節(jié)點(diǎn)客戶機(jī)網(wǎng)卡狀態(tài)管理的腳本示例”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI