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

转载于:https://my.oschina.net/u/2280272/blog/514505

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值