首页 文章 精选 留言 我的

精选列表

搜索[API密钥],共10000篇文章
优秀的个人博客,低调大师

openstack 调用API 实现云主机的IO 控制,CGroup 策略

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 # vim: tabstop= 4 shiftwidth= 4 softtabstop= 4 # Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" ); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http: //www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Single virtual machine io limit , reader 70 /MB , writer 50 /MB "" " curl -d '{"auth": {"tenantName": "admin", "passwordCredentials": {"username": "admin", "password": "admin"}}}' -H "Content-type: application/json" http: //127.0.0.1:35357/v2.0/tokens | python -m json.tool curl -v -d '{"ioctlAction": {"instance_name":"instance-0000000c","limit_reader":"40MB","limit_writer":"60MB"}}' -i http: //127.0.0.1:8774/v2/ba5a6a86a8224a70ba0ffde747d8a724/servers/e6b9cae7-8732-405d-9aaf-575643b4bbef/action -X POST -H "X-Auth-Project-Id: ba5a6a86a8224a70ba0ffde747d8a724" -H "Accept: application/json" -H "X-Auth-Token: 6f0c37595f384fd4a18766825cf49013" -H "Content-Type: application/json" "" " import time,sys,os,libvirt, trace back,re,subprocess,json from nova import log as logging from nova import flags from nova.periodic.blkio import config from nova import utils from nova.periodic.blkio import utils as blkio_utils FLAGS = flags.FLAGS LOG = logging.getLogger(__name__) class ActionIoctl(object): def __init__(self,instance_name,limit_reader,limit_writer): self.conn = libvirt.open(None) self.limitReader = int (limit_reader[ 0 :- 2 ]) self.limitWriter = int (limit_writer[ 0 :- 2 ]) self.name = instance_name self.path = FLAGS.instances_path def diskDeviceNum(self,disk): "" " Func info: Returns the number of hard disk,other is 8:0 " "" if disk == '/dev/sda1' or disk == '/dev/hda1' or disk[:- 1 ] == '/dev/sda' or disk[:- 1 ] == '/dev/hda' : return '8:0' elif disk == '/dev/sdb1' or disk == '/dev/hdb1' or disk[:- 1 ] == '/dev/sdb' or disk[:- 1 ] == '/dev/hdb' : return '8:16' elif disk == '/dev/sdc1' or disk == '/dev/hdc1' or disk[:- 1 ] == '/dev/sdc' or disk[:- 1 ] == '/dev/hdc' : return '8:32' elif disk == '/dev/sdd1' or disk == '/dev/hdd1' or disk[:- 1 ] == '/dev/sdd' or disk[:- 1 ] == '/dev/hdd' : return '8:48' else : return '8:16' def vmsPIDall(self): "" " Getting all vm port, return to " "" pid = list() try : cmds = "" "ps -ef |grep uuid|grep -v grep |awk '{print $2}'" "" pid=os.popen(cmds).readlines() return pid except Exception,e: LOG.error(_( '[-william-] Error %s' %e)) return def cgroupPath(self): '' ' Func info : Return Cgroup path ,Because the system is not the same, the Cgroup path is different also. By default , have RedHat, Centos, Ubuntu linux ... osType : The current system version , And return to ... Cpath : Cgroup path '' ' osType = open( '/etc/issue' ).readlines() for i in osType: if re.match( 'Ubuntu' ,i): Cpath = '/sys/fs/cgroup/' return Cpath elif re.match( 'CentOS' ,i): Cpath = '/cgroup/' return Cpath elif re.match( 'Red Hat' ,i): Cpath = '/cgroup/' return Cpath else : return '/sys/fs/cgroup/' def exeCmd(self,cmds): '' ' Perform system command ' '' LOG.info(_( 'exeCmd %s' %cmds)) try : exec_process = subprocess.Popen(cmds, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) exec_process.wait() rest = exec_process.stdout.read() err = exec_process.stderr.read() if err == '' : return rest else : LOG.error(_( '[-william-] return values is null' )) except Exception,e: LOG.error(_( '[-william-] Error %s' ) %e) return '' ' Geting vmName name and pid ' '' def get_vm_pid(self,name): pid = self.conn.listDomainsID() try : pid = os.popen( "" "ps -ef |grep %s |grep -v grep |awk '{print $2}'" "" %name).readlines() return int (pid[ 0 ]) except: LOG.error(_( '[-william-] Error %s' \ % trace back.format_exc())) return def _vm_pids(self): try : return os.popen( 'pidof kvm' ).read().split() except: return def work(self): "" " Func info : working func ................ Cpath : is _Cpath function return values ... path : The current virtual machine IMG file path vm_count: All of the current node number of virtual machines size : Limit size mountInfo : mounting point "" " Cpath = self.cgroupPath() vm_pid = self.get_vm_pid(self.name) LOG.info(_( '[- william -] %s , %s' %(self.name,vm_pid))) r_size = self.limitReader * 1000 * 1000 w_size = self.limitWriter * 1000 * 1000 device = blkio_utils.instance_path(self.path) diskDeviceNum = self.diskDeviceNum(device) vmTaskPath = "%s/blkio/%s" %(Cpath,self.name) utils.execute( "mkdir" , "-p" ,vmTaskPath,run_as_root=True) utils.execute( "tee" , "%s/blkio.throttle.read_bps_device" %vmTaskPath,\ process_input = "%s %s" %(diskDeviceNum,r_size),\ run_as_root=True) utils.execute( "tee" , "%s/blkio.throttle.write_bps_device" %vmTaskPath, \ process_input = "%s %s" %(diskDeviceNum,w_size) ,\ run_as_root=True) LOG.info(_( "" " [-william-] echo '%s, %s, %s , %s , %s ' write oK " "" %(self.path , device, diskDeviceNum, w_size, r_size))) utils.execute( 'tee' , '%s/tasks' %vmTaskPath,\ process_input= str(vm_pid) ,\ run_as_root=True) LOG.info(_( '[- william-] append pid %s in task' %vm_pid)) if __name__ == "__main__" : sc = ActionIoctl( 'instance-0000000c' , '40MB' , '30MB' ) sc.work() 本文转自 swq499809608 51CTO博客,原文链接:http://blog.51cto.com/swq499809608/1412022

优秀的个人博客,低调大师

MapReduce源码分析之新API作业提交(二):连接集群

MapReduce作业提交时连接集群是通过Job的connect()方法实现的,它实际上是构造集群Cluster实例cluster,代码如下: private synchronized void connect() throws IOException, InterruptedException, ClassNotFoundException { // 如果cluster为null,构造Cluster实例cluster, // Cluster为连接MapReduce集群的一种工具,提供了一种获取MapReduce集群信息的方法 if (cluster == null) { cluster = ugi.doAs(new PrivilegedExceptionAction<Cluster>() { public Cluster run() throws IOException, InterruptedException, ClassNotFoundException { return new Cluster(getConfiguration()); } }); } } 这个方法用synchronized关键字标识,处理逻辑为:如果cluster为null,构造Cluster实例cluster。 Cluster为连接MapReduce集群的一种工具,提供了一种获取MapReduce集群信息的方法,我们看下它的成员变量,如下所示: // 客户端通信协议提供者 private ClientProtocolProvider clientProtocolProvider; // 客户端通信协议实例 private ClientProtocol client; // 用户信息 private UserGroupInformation ugi; // 配置信息 private Configuration conf; // 文件系统实例 private FileSystem fs = null; // 系统路径 private Path sysDir = null; // 阶段区域路径 private Path stagingAreaDir = null; // 作业历史路径 private Path jobHistoryDir = null; // 日志 private static final Log LOG = LogFactory.getLog(Cluster.class); // 客户端通信协议提供者加载器 private static ServiceLoader<ClientProtocolProvider> frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); Cluster最重要的两个成员变量是客户端通信协议提供者ClientProtocolProvider实例clientProtocolProvider,客户端通信协议ClientProtocol实例client,而后者是依托前者的create()方法生成的。 Cluster提供了两个构造函数,如下: public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { <span style="white-space:pre"> </span>// 设置配置信息 this.conf = conf; // 获取当前用户 this.ugi = UserGroupInformation.getCurrentUser(); // 调用initialize()方法完成初始化 initialize(jobTrackAddr, conf); } 最终会调用initialize()方法完成初始化,代码如下: // 确定客户端ClientProtocol实例client private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { // 取出每个ClientProtocolProvider实例provider,通过其create()方法, // 构造ClientProtocol实例clientProtocol, // 并将两者赋值给对类应成员变量,退出循环 for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { // 通过ClientProtocolProvider的create()方法,获取客户端与集群通讯ClientProtocol实例clientProtocol if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } // 设置类成员变量clientProtocolProvider、client,并退出循环 if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; // 记录debug级别日志信息 LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { // 记录debug级别日志信息 LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } // 如果clientProtocolProvider、client任一为空,直接抛出IO异常 if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } initialize()方法唯一的一个任务就是确定客户端通信协议提供者clientProtocolProvider,并通过其create()方法构造客户端通信协议ClientProtocol实例client。 MapReduce中,ClientProtocolProvider抽象类的实现共有YarnClientProtocolProvider、LocalClientProtocolProvider两种,前者为Yarn模式,而后者为Local模式。 我们先看下Yarn模式,看下YarnClientProtocolProvider的create()方法,代码如下: @Override public ClientProtocol create(Configuration conf) throws IOException { // 如果参数mapreduce.framework.name配置的为yarn,构造一个YARNRunner实例并返回,否则返回null if (MRConfig.YARN_FRAMEWORK_NAME.equals(conf.get(MRConfig.FRAMEWORK_NAME))) { return new YARNRunner(conf); } return null; } Yarn模式下,如果参数mapreduce.framework.name配置的为yarn,构造一个YARNRunner实例并返回,否则返回null,关于YARNRunner,我们待会再讲,我们接着再看下Local模式,LocalClientProtocolProvider的create()方法,代码如下: @Override public ClientProtocol create(Configuration conf) throws IOException { // 初始化framework:取参数mapreduce.framework.name,参数未配置默认为local String framework = conf.get(MRConfig.FRAMEWORK_NAME, MRConfig.LOCAL_FRAMEWORK_NAME); // 如果framework是local,,则返回LocalJobRunner实例,并设置map任务数量为1,否则返回null if (!MRConfig.LOCAL_FRAMEWORK_NAME.equals(framework)) { return null; } conf.setInt(JobContext.NUM_MAPS, 1); return new LocalJobRunner(conf); } Local模式也是需要看参数mapreduce.framework.name的配置是否为local,是的话,返回LocalJobRunner实例,并设置map任务数量为1,否则返回null,值得一提的是,这里参数mapreduce.framework.name未配置的话,默认为local,也就是说,MapReduce需要看参数mapreduce.framework.name确定连接模式,但默认是Local模式的。 到了这里,我们就能够知道一个很重要的信息,Cluster中客户端通信协议ClientProtocol实例,要么是Yarn模式下的YARNRunner,要么就是Local模式下的LocalJobRunner,记住这点,对透彻了解MapReduce作业提交的整体流程非常重要。 好了,我们继续以Yarn模式来分析MapReduce集群连接,看下YARNRunner的实现,先看下它的成员变量,如下: // 记录工厂RecordFactory实例 private final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); // ResourceManager代理ResourceMgrDelegate实例 private ResourceMgrDelegate resMgrDelegate; // 客户端缓存ClientCache实例 private ClientCache clientCache; // 配置信息Configuration实例 private Configuration conf; // 文件上下文FileContext实例 private final FileContext defaultFileContext; 其中,最重要的一个变量就是ResourceManager代理ResourceMgrDelegate实例resMgrDelegate,Yarn模式下整个MapReduce客户端就是由它负责与Yarn集群进行通信,完成诸如作业提交、作业状态查询等过程,通过它获取集群的信息,其内部有一个YarnClient实例YarnClient,负责与Yarn进行通信,还有ApplicationId、ApplicationSubmissionContext等与特定应用程序相关的成员变量。关于ResourceMgrDelegate的详细介绍,请阅读《MapReduce源码分析ResourceMgrDelegate》一文,这里不再做详细介绍。 另外一个比较重要的变量就是客户端缓存ClientCache实例clientCache, 接下来,我们看下YARNRunner的构造函数,如下: /** * Yarn runner incapsulates the client interface of * yarn * @param conf the configuration object for the client */ public YARNRunner(Configuration conf) { // 先构造ResourceManager代理ResourceMgrDelegate实例,然后再调用两个参数的构造函数 this(conf, new ResourceMgrDelegate(new YarnConfiguration(conf))); } /** * Similar to {@link #YARNRunner(Configuration)} but allowing injecting * {@link ResourceMgrDelegate}. Enables mocking and testing. * @param conf the configuration object for the client * @param resMgrDelegate the resourcemanager client handle. */ public YARNRunner(Configuration conf, ResourceMgrDelegate resMgrDelegate) { // 先构造客户端缓存ClientCache实例,然后再调用三个参数的构造函数 this(conf, resMgrDelegate, new ClientCache(conf, resMgrDelegate)); } /** * Similar to {@link YARNRunner#YARNRunner(Configuration, ResourceMgrDelegate)} * but allowing injecting {@link ClientCache}. Enable mocking and testing. * @param conf the configuration object * @param resMgrDelegate the resource manager delegate * @param clientCache the client cache object. */ public YARNRunner(Configuration conf, ResourceMgrDelegate resMgrDelegate, ClientCache clientCache) { // 成员变量赋值 this.conf = conf; try { this.resMgrDelegate = resMgrDelegate; this.clientCache = clientCache; // 获取文件山下文FileContext实例defaultFileContext this.defaultFileContext = FileContext.getFileContext(this.conf); } catch (UnsupportedFileSystemException ufe) { throw new RuntimeException("Error in instantiating YarnClient", ufe); } } YARNRunner一共提供了三个构造函数,而我们之前说的WordCount作业提交时,其内部调用的是YARNRunner带有一个参数的构造函数,它会先构造ResourceManager代理ResourceMgrDelegate实例,然后再调用两个参数的构造函数,继而构造客户端缓存ClientCache实例,然后再调用三个参数的构造函数,而最终的构造函数只是进行简单的类成员变量赋值,然后通过FileContext的静态getFileContext()方法获取文件山下文FileContext实例defaultFileContext。 总结 MapReduce作业提交时连接集群是通过Job的connect()方法实现的,它实际上是构造集群Cluster实例cluster。Cluster为连接MapReduce集群的一种工具,提供了一种获取MapReduce集群信息的方法。在Cluster内部,有一个与集群进行通信的客户端通信协议ClientProtocol实例client,它由ClientProtocolProvider的静态create()方法构造,而Hadoop2.6.0中提供了两种模式的ClientProtocol,分别为Yarn模式的YARNRunner和Local模式的LocalJobRunner,Cluster实际上是由它们负责与集群进行通信的,而Yarn模式下,ClientProtocol实例YARNRunner对象内部有一个ResourceManager代理ResourceMgrDelegate实例resMgrDelegate,Yarn模式下整个MapReduce客户端就是由它负责与Yarn集群进行通信,完成诸如作业提交、作业状态查询等过程,通过它获取集群的信息。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码