首页 文章 精选 留言 我的

精选列表

搜索[Java应用],共10000篇文章
优秀的个人博客,低调大师

Android开发实践:自己动手编写图片剪裁应用(3)

打开图片 图片的打开主要是把各种格式的图片转换为Bitmap对象,Android通过BitmapFactory类提供了一系列的静态方法来协助完成这个操作,如下所示: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class BitmapFactory{ public static BitmapdecodeFile(StringpathName,Optionsopts); public static BitmapdecodeFile(StringpathName); public static BitmapdecodeResourceStream(Resourcesres,TypedValuevalue, InputStreamis,Rectpad,Optionsopts); public static BitmapdecodeResource(Resourcesres, int id,Optionsopts); public static BitmapdecodeResource(Resourcesres, int id); public static BitmapdecodeByteArray( byte []data, int offset, int length,Optionsopts); public static BitmapdecodeByteArray( byte []data, int offset, int length); public static BitmapdecodeStream(InputStreamis,RectoutPadding,Optionsopts); public static BitmapdecodeStream(InputStreamis); public static BitmapdecodeFileDescriptor(FileDescriptorfd,RectoutPadding,Optionsopts); public static BitmapdecodeFileDescriptor(FileDescriptorfd); } 通过这些静态方法,我们可以方便地从文件、资源、字节流等各种途径打开图片,生成Bitmap对象。下面给出一个从文件中打开图片的函数封装: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public static Bitmapload(Stringfilepath){ Bitmapbitmap= null ; try { FileInputStreamfin= new FileInputStream(filepath); bitmap=BitmapFactory.decodeStream(fin); fin.close(); } catch (FileNotFoundExceptione){ } catch (IOExceptione){ } return bitmap; } 2. 保存图片 图片的保存则主要通过Bitmap的compress方法,该方法的原型如下: 1 2 3 4 5 6 7 8 9 10 11 /** *Writeacompressedversionofthebitmaptothespecifiedoutputstream. *@paramformatTheformatofthecompressedimage *@paramqualityHinttothecompressor,0-100.0meaningcompressfor *smallsize,100meaningcompressformaxquality.Some *formats,likePNGwhichislossless,willignorethe *qualitysetting *@paramstreamTheoutputstreamtowritethecompresseddata. *@returntrueifsuccessfullycompressedtothespecifiedstream. */ public boolean compress(CompressFormatformat, int quality,OutputStreamstream) 第一个参数是图片格式,只有JPEG、PNG和WEBP三种,第二个参数是压缩质量(0~100),数值越大图片信息损失越小,第三个参数则是文件流对象。 同样,这里给出一个保存图片的函数封装: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public static void save(Bitmapbitmap,Stringfilepath){ try { FileOutputStreamfos= new FileOutputStream(filepath); bitmap.compress(CompressFormat.JPEG, 100 ,fos); bitmap.recycle(); fos.close(); } catch (FileNotFoundExceptione){ } catch (IOExceptione){ } } 3. 剪裁图片 Android中剪裁图片主要有2种方法,一种通过Bitmap的createBitmap方法来生成剪裁的图片,另一种则是通过Canvas对象来“绘制”新的图片,这里先给出代码,再分析: 1 2 3 4 5 6 7 8 9 10 11 public static Bitmapcrop(Bitmapbitmap,RectcropRect){ return Bitmap.createBitmap(bitmap,cropRect.left,cropRect.top,cropRect.width(),cropRect.height()); } public static BitmapcropWithCanvas(Bitmapbitmap,RectcropRect){ RectdestRect= new Rect( 0 , 0 ,cropRect.width(),cropRect.height()); Bitmapcropped=Bitmap.createBitmap(cropRect.width(),cropRect.height(),Bitmap.Config.RGB_565); Canvascanvas= new Canvas(cropped); canvas.drawBitmap(bitmap,cropRect,destRect, null ); return cropped; } 其实第一种方法内部实现也是利用了Canvas对象来“绘制”新的图片的,Canvas对象通过一个Bitmap对象来构建,该Bitmap即为“画布”,drawBitmap则是将源bitmap对象“画”到“画布”之中,这样就实现了数据的搬移,实现了图片的剪裁。 4. 旋转图片 Android中旋转图片同样是通过Bitmap的createBitmap方法来生成旋转后的图片,不过图片的旋转需要借助Matrix对象来协助完成,代码如下: 1 2 3 4 5 public static Bitmaprotate(Bitmapbitmap, int degrees){ Matrixmatrix= new Matrix(); matrix.postRotate(degrees); return Bitmap.createBitmap(bitmap, 0 , 0 ,bitmap.getWidth(),bitmap.getHeight(),matrix, true ); } 当然,图片的旋转也是可以通过Canvas来“绘制”,由于图片旋转会导致边界坐标发生变化,所以需要以图片中心点坐标为中心来旋转,具体实现见如下代码: 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 public static BitmaprotateWithCanvas(Bitmapbitmap, int degrees){ int destWidth,destHeight; float centerX=bitmap.getWidth()/ 2 ; float centerY=bitmap.getHeight()/ 2 ; //Wewanttodotherotationatorigin,butsincethebounding //rectanglewillbechangedafterrotation,sothedeltavalues //arebasedonold&newwidth/heightrespectively. Matrixmatrix= new Matrix(); matrix.preTranslate(-centerX,-centerY); matrix.postRotate(degrees); if (degrees/ 90 % 2 == 0 ){ destWidth=bitmap.getWidth(); destHeight=bitmap.getHeight(); matrix.postTranslate(centerX,centerY); } else { destWidth=bitmap.getHeight(); destHeight=bitmap.getWidth(); matrix.postTranslate(centerY,centerX); } Bitmapcropped=Bitmap.createBitmap(destWidth,destHeight,Bitmap.Config.RGB_565); Canvascanvas= new Canvas(cropped); canvas.drawBitmap(bitmap,matrix, null ); return cropped; } 本文转自 Jhuster 51CTO博客,原文链接:http://blog.51cto.com/ticktick/1604074,如需转载请自行联系原作者

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

关于iOS应用设计的一些最佳实践

时刻铭记着views的生命周期 不要在init的方法中访问self.view 使用data source protocols(数据源协议)来明显地将data从view上区分开来 UIViewController 使用已经存在的navigationitem对象 NSObject 在头文件中仅暴露公有属性和方法 Debugging 使用lldb来进行测试 使用NSZombieEnabled来发现内存泄露 ----------------------------------------------------------------------------------------------------------------------- 时刻铭记着views的生命周期 不断地提醒自己,在任何时候,你的view都可能被销毁 (1) 不要在init的方法中访问self.view 你永远不应该在你的controller的init方法中访问self.view。这么做总是会导致很多难于调试的bug,因为在收到一个内存警告之后init的逻辑将无法再次执行一遍。 考虑下面这个简单的例子: - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { self.view.backgroundColor = [UIColor underPageBackgroundColor]; } return self; } 想象一下这个controller是一个navigation stack(注:iOS中使用栈的结构来管理那些navigationController相关的视图对象)的根对象,与此同时一个内存警告发生了(收到内存警告如果没有正确处理,iOS系统会销毁一些视图以释放内存空间)。当我们返回到该控制器的时候,该视图将不再以underPageBackgroundColor作为其背景色。这会给调试带来麻烦,即便是对于那些有经验的iOS工程师也是如此。 (2) 使用data source protocols(数据源协议)来明显地将数据从视图上区分开来 当你正在设计一个视图来与数据集进行交互的时候,你总是应该通过一个data source protocol来获取数据,而不是通过暴露访问器(setter)的形式。视图不是数据的容器,所以不应该让它们承受这样的“罪责”。正确的做法是,视图应该被当做一个“失去存在感”的可扩展的组件,在任何时候都是。 作为一个一般性的通用法则,在视图上的任何超出静态展现的信息都应该通过data source或者delegate来获取。 UILabel就是一个不需要datasource的视图,它是个很好的示例。它所有的属性通常都被设置一次,并且通常在视图的生命周期内都不期待被改变。 而从另一方面来说,UITableView是一个需要data source来提取数据的好例子。让我们想象一下当我们使用UITableView的时候不是通过一个datasource而是仅仅通过提供setter的情况将会是什么样子。 如果真是这样设计的话,当开发者企图使用table view对象来存储他们的数据的时候,将会导致不可避免的滥用。当收到内存警告,table view 不可避免地被释放时,数据也将一同消失(因为它通过setter存储在tableview对象内部)。这意味着我们需要存储的数据能够在任何情况下北table view的多个实例在其生命周期内可以访问。 UIViewController view controller用来完成model与view之间的绑定 (1)使用已存在的navigation item对象 每一个UIViewController的实例都有一个navigationItem属性,它应该被用来指定左/右导航按钮以及标题视图。你不应该创建一个UINavigationItem 对象,因为在你访问self.navigationItem的时候UIViewController的基类实现将自动帮你创建一个。简单地使用self.navigationItem来访问并为其设置属性: // UIViewController will automatically create the navigationItem object. self.navigationItem.rightBarButtonItem = doneButton; NSObject (1) 在头文件中仅暴露公有属性和方法 obj-c允许你在一个category interface(.m文件中)定义私有的属性。利用这个特性提供更好地访问限制吧。 这等价于通过@provate进行定义,并且能够带来一些额外的好处——对于代码的修改不需要重新编译并且不影响其他对象的内部结构。在一个大型项目中,这是大有裨益的。 示例: ViewController.h @interface ViewController : UIViewController @property (nonatomic, readonly, assign) NSInteger objectId; @end ViewController.m #import "ViewController.h" @interface ViewController() @property (nonatomic, readwrite, assign) NSInteger objectId; // Notice that this property doesn't need to be in the .h. Objective-C will create this // property on the fly! @property (nonatomic, readwrite, retain) UILabel* objectLabel; @end @implementation ViewController @synthesize objectId; @synthesize objectLabel; ... @end Debugging (1)使用lldb来进行测试 lldb允许你检查类的属性,不需要在对象的实例上有明确地定义 (2)使用NSZombieEnabled来发现内存泄露 当NSZombieEnabled被使用,那些从内存中被释放的对象都将被保存为“zombies”。如果在未来的某个时间你企图再次访问这些已被释放的对象。这对于你去判断在什么地方发生内存泄露将会大有帮助。 (注:关于这两个debug的配置,请自行google) 原文发布时间为:2012-09-10 本文作者:vinoYang 本文来自云栖社区合作伙伴CSDN博客,了解相关信息可以关注CSDN博客。

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

企业私有云应用之使用OZ制作openstack镜像

最近工作忙,好久没写博客,现在正好有空介绍一下我这里使用私有云的经验。 现在分享一下如何使用oz自动化制作openstack镜像,下面有我自己制作centos 6.4 6.5 6.7 7.2与ubuntu 12.04.5与14.04.4的模板,模板也存放到github里,地址是https://github.com/dl528888/oz_create_openstack_image_templates。 之前使用镜像要不使用别人做好的,要不是自己制作,但很麻烦,现在使用oz可以简化操作,定制一个模板(类似cobbler)的就可以自动化制作了,十分方便。 官方地址是https://github.com/clalancette/oz/ 下面是介绍如何安装 1、安装epel源 1 2 rpm-ivhhttp: //mirrors .sohu.com /fedora-epel/6/x86_64/epel-release-6-8 .noarch.rpm yum install -yoz 如果还是没有生效,可以使用下面的配置在安装 1 2 3 4 5 6 7 8 9 [epel] name=ExtraPackages for EnterpriseLinux6-$basearch #baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch baseurl=http: //mirrors .sohu.com /fedora-epel/6/ $basearch ##mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch failovermethod=priority enabled=1 gpgcheck=0 gpgkey= file : ///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 2、启动虚拟网络 1 virshnet-startdefault 如果出现下面错误 本文转自 reinxu 51CTO博客,原文链接:http://blog.51cto.com/dl528888/1862568,如需转载请自行联系原作者

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

docker高级应用之单机持久化固定容器IP

过完年了,快1个月没有写博客,现在给大家分享一下我是如何在单机环境,实现持久化固定容器IP。 我是去年6月份开始玩docker,到现在已经9个月了,docker的最新版本也到了1.5.目前我这里对docker已经放到测试环境给研发使用,目前感觉最大的问题就是容器手动重启或者异常关闭后在启动容器,那么容器的ip就回变化(这个是使用默认的docker0做桥接),如果使用pipework手动配置ip,也得重新在来一遍,很是麻烦,所以我写了一个程序来自动化的解决这个问题。 一、程序介绍 使用到的程序有2个: 1、创建容器程序,名字是create_docker_container_use_static_ip.sh,使用shell脚本编写。 2、监控容器状态并自动给重启没有ip的容器设置ip,名字是auto_check_modify_container.py,使用python编写。 创建容器程序的逻辑: 1、运行创建脚本来创建docker container; 2、创建的信息会写入到etcd里进行保存; 3、根据配置信息来创建具体的container。 其中我程序使用openvswitch来坐桥接,并对不同vlan做不同的网段设置。 监控容器并给自动重启设置ip程序逻辑: 1、从etcd里获取容器的信息; 2、根据第一步的信息,进行nmap扫描ssh服务是否启动,未启动的转给下一步; 3、收到上一步的ip,然后根据etcd的容器信息进行重新pipework配置之前的固定ip。 下面是创建容器程序脚本内容 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 #!/bin/bash #author:DengLei #email:dl528888@gmail.com #thisscriptiscreatenewdockercontainerandusepipeworkaddstaticip,whencontainerisrestart,italsouselaststaticip container=$1 images=$2 daemon_program=$3 vlan_tag=$4 #ip_pool='172.16.10.1/24' bridge=ovs2 default_vlan=1 default_vlan_ip= '172.16.0.1/24' email= '244979152@qq.com' local_ip=` /sbin/ifconfig | grep 'inet' | grep -Ev '(127|117|211|172|::1|fe)' | awk '{print$2}' | head -n1` if [-z$1]||[-z$2]; then echo "Usage:container_namecontainer_imagevlan_tag(default:1)" echo "Example:Iwantcreatenewdockercontainertest1centos6:latestsupervisordvlan100" echo "Thecommandis:bash`basename$0`test1centos6:latestsupervisord100" exit 1 fi [`docker ps -a| grep - v "NAMES" | awk '{print$NF}' | grep "$container" &>> /dev/null && echo 0|| echo 1`- eq 0]&& echo "Thecontainer$containerisexist!" && exit 1 [` which pipework&> /dev/null && echo 0|| echo 1`- eq 1]&& echo "Ican'tfindpipework,pleaseinstallit!" && exit 1 if [-z$3]; then vlan_tag=${default_vlan} fi #createnewdockercontainer dockerrun--restartalways-d--net= "none" --name= "$container" $images$daemon_program&>> /dev/null #checkopenvswitchbridgeexist if [`ovs-vsctllist-br| grep ${bridge}&> /dev/null && echo 0|| echo 1`- eq 1]; then ovs-vsctladd-br${bridge} fi #setupdefaultvlaninfo check_default_vlan_exist=`etcdctlget /app/docker/ ${local_ip} /vlan ${default_vlan} /gateway 2> /dev/null || echo 1` if [${check_default_vlan_exist}= "1" ]; then ovs-vsctladd-port$bridgevlan${default_vlan}tag=${default_vlan}-- set interfacevlan${default_vlan} type =internal #ifconfigvlan${default_vlan}${default_vlan_ip} iplink set vlan${default_vlan}up ipaddradd$default_vlan_ipdevvlan${default_vlan} etcdctl set /app/docker/ ${local_ip} /vlan ${default_vlan} /nowip $default_vlan_ip&>> /dev/null etcdctl set /app/docker/ ${local_ip} /vlan ${default_vlan} /gateway $default_vlan_ip&>> /dev/null etcdctl set /app/docker/now_vlan_ip $default_vlan_ip&>> /dev/null fi #setupnewvlaninfo new_vlan_gateway_ip=`etcdctlget /app/docker/ ${local_ip} /vlan ${vlan_tag} /gateway 2> /dev/null || echo 1` if [${new_vlan_gateway_ip}= "1" ]; then sleep 1 now_vlan_ip=`etcdctlget /app/docker/now_vlan_ip ` new_vlan_ip=$( awk - v new_ip=` echo $now_vlan_ip| cut -d/-f1| awk -F '.' '{print$1"."$2"."$3+1"."$4}' `- v new_ip_netmask=` echo $now_vlan_ip| cut -d/-f2` 'BEGIN{printnew_ip"/"new_ip_netmask}' ) ovs-vsctladd-port$bridgevlan${vlan_tag}tag=${vlan_tag}-- set interfacevlan${vlan_tag} type =internal iplink set vlan${vlan_tag}up ipaddradd${new_vlan_ip}devvlan${vlan_tag} #ifconfigvlan${vlan_tag}${new_vlan_ip} etcdctl set /app/docker/now_vlan_ip ${new_vlan_ip}&>> /dev/null etcdctl set /app/docker/ ${local_ip} /vlan ${vlan_tag} /gateway ${new_vlan_ip}&>> /dev/null etcdctl set /app/docker/ ${local_ip} /vlan ${vlan_tag} /nowip ${new_vlan_ip}&>> /dev/null new_vlan_gateway_ip=${new_vlan_ip} fi #calculatenewip sleep 1 now_container_ip=`etcdctlget /app/docker/ ${local_ip} /vlan ${vlan_tag} /nowip ` echo "nowcontaineripis:$now_container_ip" new_container_ip=$( awk - v new_ip=` echo $now_container_ip| cut -d/-f1| awk -F '.' '{print$1"."$2"."$3"."$4+1}' `- v new_ip_netmask=` echo $now_container_ip| cut -d/-f2` 'BEGIN{printnew_ip"/"new_ip_netmask}' ) etcdctl set /app/docker/ ${local_ip} /vlan ${vlan_tag} /nowip $new_container_ip&> /dev/null echo "finishcalculatenewip!" create_time=` date + "%Y-%m-%d%T" ` ` which pipework`$bridge$container${new_container_ip}@` echo ${new_vlan_gateway_ip}| awk -F '/' '{print$1}' `@${vlan_tag} etcdctl set /app/docker/ ${local_ip} /vlan ${vlan_tag} /container/ ${container} "{'Physics_ip':'${local_ip}','Container_name':'${container}','Container_ip':'${new_container_ip}','Container_vlan':'${vlan_tag}','Container_vlan_gateway':'${new_vlan_gateway_ip}','Container_create':'${create_time}','Container_status':'running'}" 注意:如果想使用本程序,客户端必须安装openvswitch、etcd与etcdctl、pipework。 监控容器并给自动重启设置ip程序脚本内容: 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 #!/usr/bin/envpython #author:DengLei #email:dl528888@gmail.com import sys import nmap import multiprocessing import time import socket,struct,fcntl import etcd import re fromdocker import Client import subprocess defget_local_ip(iface= 'em1' ): sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sockfd=sock.fileno() SIOCGIFADDR=0x8915 ifreq=struct.pack( '16sH14s' ,iface,socket.AF_INET, '\x00' *14) try: res=fcntl.ioctl(sockfd,SIOCGIFADDR,ifreq) except: return None ip=struct.unpack( '16sH2x4s8x' ,res)[2] return socket.inet_ntoa(ip) defget_etcd_info(key): etcd_result=[] r=etcd_client. read ( '%s%s' %(docker_etcd_key,local_ip),recursive=True,sorted=True) for child in r.children: if child. dir isnotTrueand "Container_name" in child.value: etcd_result.append(child.value) return etcd_result defcheck_by_nmap(ip,port): check_result=len(nm.scan( '%s' %ip, '%s' %port)[ 'scan' ]) if check_result==0: msg= '%s' %(ip) return msg defdocker_container_stop(): docker_container=docker_client.containers(all=True) container_name=[] container_stop_name=[] for i in docker_container: if re.match( 'Exited' ,i[ 'Status' ]): container_name.append(i[ 'Names' ]) for b in container_name: for c in b: container_stop_name.append(c) return container_stop_name defdocker_container_all(): docker_container=docker_client.containers(all=True) container_name=[] container_stop_name=[] for i in docker_container: container_name.append(i[ 'Names' ]) for b in container_name: for c in b: container_stop_name.append(c) return container_stop_name if __name__== "__main__" : nm=nmap.PortScanner() etcd_client=etcd.Client(host= '127.0.0.1' ,port=4001) docker_client=Client(base_url= 'unix://var/run/docker.sock' ,version= '1.15' ,timeout=10) local_ip=get_local_ip( 'ovs1' ) bridge= 'ovs2' docker_etcd_key= '/app/docker/' port= '22' ip_list=[] now_etcd_result=get_etcd_info(docker_etcd_key) docker_container_stop_name=docker_container_stop() docker_container_all_name=docker_container_all() for i in range(len(now_etcd_result)): now_info= eval (now_etcd_result[i]) key= '%s%s/vlan%s/container/%s' %(docker_etcd_key,local_ip,now_info[ 'Container_vlan' ],now_info[ 'Container_name' ]) if '/' +now_info[ 'Container_name' ]not in docker_container_stop_nameandnow_info[ 'Container_status' ]!= 'delete' : ip_list.append( eval (now_etcd_result[i])[ 'Container_ip' ]. split ( '/' )[0]) if now_info[ 'Container_status' ]== 'stop' : now_info[ 'Container_status' ]= 'running' etcd_client.write(key,now_info) else : now_info[ 'Container_status' ]= 'stop' etcd_client.write(key,now_info) if '/' +now_info[ 'Container_name' ]not in docker_container_all_name: print '%s%swilldelete,becausedockerclienthaddeleted!' %( time .strftime( '%Y-%m-%d%T' ),key) now_info[ 'Container_status' ]= 'delete' etcd_client.write(key,now_info) ip_list=list( set (ip_list)) if len(ip_list)==1: num=1 elif len(ip_list)>=4andlen(ip_list)<=8: num=4 elif len(ip_list)>8andlen(ip_list)<=20: num=8 else : num=15 pool=multiprocessing.Pool(processes=num) scan_result=[] for i in ip_list: pool.apply_async(check_by_nmap,(i,port,)) scan_result.append(pool.apply_async(check_by_nmap,(i,port,))) pool.close() pool. join () result=[] for res in scan_result: if res.get()isnotNone: result.append(res.get()) result=list( set (result)) if len(result)<=0: print '%sEverythingisallright!' % time .strftime( '%Y-%m-%d%T' ) sys. exit (1) else : print '%scontainerneedmodifycontainerstaticipis:%s' %( time .strftime( '%Y-%m-%d%T' ),result) for i in range(len(now_etcd_result)): now_info= eval (now_etcd_result[i]) if (now_info[ 'Container_ip' ]). split ( '/' )[0] in result: modify_container=subprocess.Popen( "`whichpipework`%s%s%s@%s@%s&>>/dev/null&&echo0||echo1" %(bridge,now_info[ 'Container_name' ],now_info[ 'Container_ip' ],now_info[ 'Container_vlan_gateway' ]. split ( '/' )[0],now_info[ 'Container_vlan' ]),shell=True,stdout=subprocess.PIPE) if (modify_container.stdout.readlines()[0]).strip( '\n' )==0: print 'container_name:%scontainer_ip:%smodifystaticipisfail!' %(now_info[ 'Container_name' ],now_info[ 'Container_ip' ]) else : print 'container_name:%scontainer_ip:%smodifystaticipissuccess!' %(now_info[ 'Container_name' ],now_info[ 'Container_ip' ]) 注意:使用本脚本必须安装nmap、etcd、docker模块。 其中python里nmap的安装方法是 1 easy_installpython-nmap 其中python里etcd的安装方法是 安装基础库 1 yum install libffilibffi-develpython-devel 安装程序 1 2 3 gitclonehttps: //github .com /jplana/python-etcd .git cd python-etcd pythonsetup.py install 其中python里docker的安装方法是 1 easy_installdocker-py 二、效果展示 需求: 创建主机test1、test2、test3、test4,需要test1与test2属于vlan100,test3与test4属于vlan300,架构图如下 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ovs2 | | ----------------- || || vlan100(tag100)vlan300(tag300) || || --------------------------------- |||| |||| test1test2test3test4 (tag100)(tag100)(tag300)(tag300) 下面是操作 1、创建ovs1、ovs2网桥,其中em1绑定到ovs1走内网,ovs2是容器的网络 1 2 3 4 5 6 ovs-vsctladd-brovs1 ovs-vsctladd-brovs2 ovs-vsctladd-portovs1em1 iplink set ovs1up ifconfig em10 ifconfig ovs110.10.17.3 2、创建test1、test2、test3、test4的容器 1 2 3 4 5 6 7 8 [root@docker-test3~] #shcreate_docker_container_use_static_ip.shtest1docker.ops-chukong.com:5000/centos6-http:new/usr/bin/supervisord100 { 'Physics_ip' : '10.10.17.3' , 'Container_name' : 'test1' , 'Container_ip' : '172.16.1.2/24' , 'Container_vlan' : '100' , 'Container_vlan_gateway' : '172.16.1.1/24' , 'Container_create' : '2015-03-0214:59:59' , 'Container_status' : 'running' } [root@docker-test3~] #shcreate_docker_container_use_static_ip.shtest2docker.ops-chukong.com:5000/centos6-http:new/usr/bin/supervisord100 { 'Physics_ip' : '10.10.17.3' , 'Container_name' : 'test2' , 'Container_ip' : '172.16.1.3/24' , 'Container_vlan' : '100' , 'Container_vlan_gateway' : '172.16.1.1/24' , 'Container_create' : '2015-03-0215:00:09' , 'Container_status' : 'running' } [root@docker-test3~] #shcreate_docker_container_use_static_ip.shtest3docker.ops-chukong.com:5000/centos6-http:new/usr/bin/supervisord300 { 'Physics_ip' : '10.10.17.3' , 'Container_name' : 'test3' , 'Container_ip' : '172.16.2.2/24' , 'Container_vlan' : '300' , 'Container_vlan_gateway' : '172.16.2.1/24' , 'Container_create' : '2015-03-0215:00:22' , 'Container_status' : 'running' } [root@docker-test3~] #shcreate_docker_container_use_static_ip.shtest4docker.ops-chukong.com:5000/centos6-http:new/usr/bin/supervisord300 { 'Physics_ip' : '10.10.17.3' , 'Container_name' : 'test4' , 'Container_ip' : '172.16.2.3/24' , 'Container_vlan' : '300' , 'Container_vlan_gateway' : '172.16.2.1/24' , 'Container_create' : '2015-03-0215:00:31' , 'Container_status' : 'running' } 这个脚本第一个参数是创建的容器名,第二个参数是docker images,第三个参数是运行命令,第四个参数是vlan。 下面是当前docker信息 1 2 3 4 5 6 [root@docker-test3~] #dockerps-a CONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES 386b4180b3d0docker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor AboutaminuteagoUpAboutaminutetest4 92fee54ec498docker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor AboutaminuteagoUpAboutaminutetest3 4dc84301894adocker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor AboutaminuteagoUpAboutaminutetest2 45d4a73c6ed0docker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor 2minutesagoUp2minutestest1 下面是openvswitch的信息 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 [root@docker-test3~] #ovs-vsctlshow d895d78b-8c89-49bc-b429-da6a4a2dcb3a Bridge "ovs2" Port "vlan300" tag:300 Interface "vlan300" type :internal Port "ovs2" Interface "ovs2" type :internal Port "veth1pl11491" tag:100 Interface "veth1pl11491" Port "veth1pl12003" tag:300 Interface "veth1pl12003" Port "vlan100" tag:100 Interface "vlan100" type :internal Port "veth1pl12251" tag:300 Interface "veth1pl12251" Port "veth1pl11788" tag:100 Interface "veth1pl11788" Port "vlan1" tag:1 Interface "vlan1" type :internal Bridge "ovs1" Port "em1" Interface "em1" Port "ovs1" Interface "ovs1" type :internal ovs_version: "2.3.1" 下面是etcd的信息 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 [root@docker-test3~] #etcdctlls/--recursive|grepdocker|grep"10.10.17.3/" /app/docker/ip/vlan/10 .10.17.3 /gate_way /app/docker/ip/vlan/10 .10.17.3 /now_ip /app/docker/10 .10.17.3 /vlan300 /app/docker/10 .10.17.3 /vlan300/container /app/docker/10 .10.17.3 /vlan300/container/test3 /app/docker/10 .10.17.3 /vlan300/container/test4 /app/docker/10 .10.17.3 /vlan300/gateway /app/docker/10 .10.17.3 /vlan300/nowip /app/docker/10 .10.17.3 /vlan1 /app/docker/10 .10.17.3 /vlan1/gateway /app/docker/10 .10.17.3 /vlan1/nowip /app/docker/10 .10.17.3 /vlan100 /app/docker/10 .10.17.3 /vlan100/gateway /app/docker/10 .10.17.3 /vlan100/nowip /app/docker/10 .10.17.3 /vlan100/container /app/docker/10 .10.17.3 /vlan100/container/test1 /app/docker/10 .10.17.3 /vlan100/container/test2 查看test1的信息 1 2 [root@docker-test3~] #etcdctlget/app/docker/10.10.17.3/vlan100/container/test1 { 'Physics_ip' : '10.10.17.3' , 'Container_name' : 'test1' , 'Container_ip' : '172.16.1.2/24' , 'Container_vlan' : '100' , 'Container_vlan_gateway' : '172.16.1.1/24' , 'Container_create' : '2015-03-0214:59:59' , 'Container_status' : 'running' } 跟创建容器的信息一样 进入容器,然后查看设置ip情况 1 2 3 4 5 6 7 8 [root@docker-test3~] #dockerexectest1ifconfigeth1|grep"inetaddr" inetaddr:172.16.1.2Bcast:0.0.0.0Mask:255.255.255.0 [root@docker-test3~] #dockerexectest2ifconfigeth1|grep"inetaddr" inetaddr:172.16.1.3Bcast:0.0.0.0Mask:255.255.255.0 [root@docker-test3~] #dockerexectest3ifconfigeth1|grep"inetaddr" inetaddr:172.16.2.2Bcast:0.0.0.0Mask:255.255.255.0 [root@docker-test3~] #dockerexectest4ifconfigeth1|grep"inetaddr" inetaddr:172.16.2.3Bcast:0.0.0.0Mask:255.255.255.0 可以看到ip都是之前设置的 然后在test1里ping外网与test2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 [root@docker-test3~] #dockerexectest1ping-c1www.baidu.com PINGwww.a.shifen.com(180.149.131.205)56(84)bytesofdata. 64bytesfrom180.149.131.205:icmp_seq=1ttl=54 time =1.94ms ---www.a.shifen.com ping statistics--- 1packetstransmitted,1received,0%packetloss, time 12ms rttmin /avg/max/mdev =1.948 /1 .948 /1 .948 /0 .000ms [root@docker-test3~] #dockerexectest1ping-c1172.16.1.3 PING172.16.1.3(172.16.1.3)56(84)bytesofdata. 64bytesfrom172.16.1.3:icmp_seq=1ttl=64 time =0.431ms ---172.16.1.3 ping statistics--- 1packetstransmitted,1received,0%packetloss, time 0ms rttmin /avg/max/mdev =0.431 /0 .431 /0 .431 /0 .000ms 可以看到都是通的 在从test3里ping外网与test4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 [root@docker-test3~] #dockerexectest3ping-c1www.baidu.com PINGwww.a.shifen.com(180.149.131.236)56(84)bytesofdata. 64bytesfrom180.149.131.236:icmp_seq=1ttl=54 time =2.19ms ---www.a.shifen.com ping statistics--- 1packetstransmitted,1received,0%packetloss, time 12ms rttmin /avg/max/mdev =2.197 /2 .197 /2 .197 /0 .000ms [root@docker-test3~] #dockerexectest3ping-c1172.16.2.3 PING172.16.2.3(172.16.2.3)56(84)bytesofdata. 64bytesfrom172.16.2.3:icmp_seq=1ttl=64 time =0.504ms ---172.16.2.3 ping statistics--- 1packetstransmitted,1received,0%packetloss, time 0ms rttmin /avg/max/mdev =0.504 /0 .504 /0 .504 /0 .000ms 也是通的 3、关闭test1并测试 1 2 3 4 5 6 7 8 9 10 11 12 13 [root@docker-test3~] #dockerstoptest1 test1 [root@docker-test3~] #dockerps-a CONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES 386b4180b3d0docker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor 12minutesagoUp12minutestest4 92fee54ec498docker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor 12minutesagoUp12minutestest3 4dc84301894adocker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor 12minutesagoUp12minutestest2 45d4a73c6ed0docker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor 12minutesagoExited(0)2secondsagotest1 [root@docker-test3~] #ping-c2172.16.1.2 PING172.16.1.2(172.16.1.2)56(84)bytesofdata. ---172.16.1.2 ping statistics--- 2packetstransmitted,0received,100%packetloss, time 999ms 可以看到test1关闭了,给予的ip也不能通了,下面启动容器,然后使用我自动检测与重新设置容器ip 1 2 3 4 5 6 7 8 9 10 11 [root@docker-test3~] #dockerstarttest1 test1 [root@docker-test3~] #dockerps-a CONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES 386b4180b3d0docker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor 13minutesagoUp13minutestest4 92fee54ec498docker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor 13minutesagoUp13minutestest3 4dc84301894adocker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor 13minutesagoUp13minutestest2 45d4a73c6ed0docker.ops-chukong.com:5000 /centos6-http :new" /usr/bin/supervisor 13minutesagoUp2secondstest1 [root@docker-test3~] #pythonauto_check_modify_container.py 2015-03-0215:14:03containerneedmodifycontainerstaticipis:[ '172.16.1.2' ] container_name:test1container_ip:172.16.1.2 /24 modifystaticipissuccess! 可以看到启动容器后,程序自动搜集之前的ip信息,并重新配置了 在test1里测试 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 [root@docker-test3~] #dockerexectest1ifconfigeth1|grep"inetaddr" inetaddr:172.16.1.2Bcast:0.0.0.0Mask:255.255.255.0 [root@docker-test3~] #dockerexectest1ping-c1www.baidu.com PINGwww.a.shifen.com(180.149.131.236)56(84)bytesofdata. 64bytesfrom180.149.131.236:icmp_seq=1ttl=54 time =2.18ms ---www.a.shifen.com ping statistics--- 1packetstransmitted,1received,0%packetloss, time 12ms rttmin /avg/max/mdev =2.183 /2 .183 /2 .183 /0 .000ms [root@docker-test3~] #dockerexectest1ping-c1172.16.1.3 PING172.16.1.3(172.16.1.3)56(84)bytesofdata. 64bytesfrom172.16.1.3:icmp_seq=1ttl=64 time =0.382ms ---172.16.1.3 ping statistics--- 1packetstransmitted,1received,0%packetloss, time 0ms rttmin /avg/max/mdev =0.382 /0 .382 /0 .382 /0 .000ms 测试都没有问题 大家以后使用的时候,可以先使用我的程序创建容器,然后把检测程序放到crontab里,每分钟自动运行,这样就能实现持久化固定ip。 本文转自 reinxu 51CTO博客,原文链接:http://blog.51cto.com/dl528888/1616527,如需转载请自行联系原作者

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

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

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

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

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