nginx日志切割

原文

第一步就是重命名日志文件,不用担心重命名后nginx找不到日志文件而丢失日志。在你未重新打开原名字的日志文件前,nginx还是会向你重命名的文件写日志,linux是靠文件描述符而不是文件名定位文件。

第二步向nginx主进程发送USR1信号。

nginx主进程接到信号后会从配置文件中读取日志文件名称,重新打开日志文件(以配置文件中的日志名称命名),并以工作进程的用户作为日志文件的所有者。

重新打开日志文件后,nginx主进程会关闭重名的日志文件并通知工作进程使用新打开的日志文件。

工作进程立刻打开新的日志文件并关闭重名名的日志文件。

然后你就可以处理旧的日志文件了。

#nginx日志切割脚本

#!/bin/bash
#设置日志文件存放目录
logs_path="/usr/local/nginx/logs/"
#设置pid文件
pid_path="/usr/local/nginx/nginx.pid"

#重命名日志文件
mv ${logs_path}access.log ${logs_path}access_$(date -d "yesterday" +"%Y%m%d").log

#向nginx主进程发信号重新打开日志
kill -USR1 `cat ${pid_path}`

crontab 设置作业

0 0 * bash /usr/local/nginx/nginx_log.sh
这样就每天的0点0分把nginx日志重命名为日期格式,并重新生成今天的新日志文件。

Android Proguard混淆打包经验总结

作为一名Android开发,应该了解并尝试给自己的项目进行Proguard混淆打包。项目经过Proguard混淆打包后,会发现apk包体积会变小,也就是混淆可以使得apk瘦身;并且反编译apk的时候会发现, 项目中的源码都被处理过,进一步保障了apk的安全;这就是我所理解的Proguard混淆打包的两个优点。不过,想要真正给自己的项目进行Proguard混淆打包,可不是一件容易的事情,真正尝试去做了,才会发现有好多问题需要去解决,毕竟,混淆打包是针对特定的项目,每个项目需要混淆的代码都是有区别的。不过,所有apk混淆打包,也有一些通用的规则处理,像这些规则,就可以自己记录下来,这样其他项目混淆打包的时候就可以复制粘贴使用混淆代码了。好了,进入正题,如何给自己的项目量身定制一套Proguard混淆代码了?

关于Proguard混淆,给APP瘦身,Google官方也给出了文档给了大致解释,大家有兴趣可以看看,纯英文(够呛),不过怎么在Android Studio配置Proguard混淆,还是可以看懂的:

https://developer.android.com/studio/build/shrink-code.html

我们可以从这些方面对apk瘦身:

1)冗余的代码,比如多余的jar包代码;

2)未使用的静态代码;

3)资源代码的冗余;

4)native code

5)图片资源的优化和压缩

ProGuard混淆打包,解决的问题主要针对第一点,一般项目进行ProGuard混淆打包后,apk的体积会减小200-500KB左右。

继续阅读“Android Proguard混淆打包经验总结”

使用proguard混淆android代码

保留选项(配置不进行处理的内容)

-keep {Modifier} {class_specification} 保护指定的类文件和类的成员
-keepclassmembers {modifier} {class_specification} 保护指定类的成员,如果此类受到保护他们会保护的更好
-keepclasseswithmembers {class_specification} 保护指定的类和类的成员,但条件是所有指定的类和类成员是要存在。
-keepnames {class_specification} 保护指定的类和类的成员的名称(如果他们不会压缩步骤中删除)
-keepclassmembernames {class_specification} 保护指定的类的成员的名称(如果他们不会压缩步骤中删除)
-keepclasseswithmembernames {class_specification} 保护指定的类和类的成员的名称,如果所有指定的类成员出席(在压缩步骤之后)
-printseeds {filename} 列出类和类的成员-keep选项的清单,标准输出到给定的文件

压缩

-dontshrink 不压缩输入的类文件
-printusage {filename}
-whyareyoukeeping {class_specification}

优化

-dontoptimize 不优化输入的类文件
-assumenosideeffects {class_specification} 优化时假设指定的方法,没有任何副作用
-allowaccessmodification 优化时允许访问并修改有修饰符的类和类的成员

继续阅读“使用proguard混淆android代码”

ubuntu禁止apache开机自启动

# 移除apache2自启动脚本,
# 参数-f是为了解决 update-rc.d: /etc/init.d/apache2 exists during rc.d purge的问题

sudo update-rc.d -f apache2 remove
 
# 同时也可以方便的恢复自启动脚本
sudo update-rc.d apache2 defaults
 
# 或者编辑文件 /etc/default/apache2 设置内容中的 NO_BOOT 值为 1.

ThinkPHP的CBD模式

thinkphp使用核心c(core)+行为b(behavior)+驱动d(driver)三种方式架构。

Core(核心)

ThinkPHP的核心部分包括核心函数库、惯例配置、核心类库(包括基础类和内置驱动及核心行为)

Driver(驱动)

//包含以下文件
ThinkPHP/Library/Think/Cache/Driver // 缓存驱动类库
ThinkPHP/Library/Think/Db/Driver // 数据库驱动类库
ThinkPHP/Library/Think/Log/Driver // 日志记录驱动类库
ThinkPHP/Library/Think/Session/Driver // Session驱动类库
ThinkPHP/Library/Think/Storage/Driver // 存储驱动类库
ThinkPHP/Library/Think/Template/Driver // 第三方模板引擎驱动类库
ThinkPHP/Library/Think/Template/TagLib // 内置模板引擎标签库扩展类库
Behavior(行为)

什么是行为,行为是应用的执行过程中的一个动作一个处理。有些行为具有位置共性。
行为发生的位置可以称为标签或钩子。

系统核心的一些标签

app_init 应用初始化标签位
module_check 模块检测标签位(**3.2.1版本新增**)
path_info PATH_INFO检测标签位
app_begin 应用开始标签位
action_name 操作方法名标签位
action_begin 控制器开始标签位
view_begin 视图输出开始标签位
view_template 视图模板解析标签位
view_parse 视图解析标签位
template_filter 模板解析过滤标签位
view_filter 视图输出过滤标签位
view_end 视图输出结束标签位
action_end 控制器结束标签位
app_end 应用结束标签位

自定义标签

// 添加my_tag 标签侦听
tag('my_tag'); 
// 下面的写法作用一致
ThinkHook::listen('my_tag');

tag函数用于设置某个标签位,可以传入并且只接受一个参数,如果需要传入多个参数,请使用数组,

tag('my_tag',$params); // 添加my_tag 标签侦听

该参数为引用传值,所以只能传入变量,因此下面的传值是错误的:

tag('my_tag','param'); // 添加my_tag 标签侦听行为的定义

行为定义
自定义的扩展行为可以放在核心或者应用目录,只要遵循命名空间的定义规则即可。
行为类的命名采用:行为名称(驼峰法,首字母大写)+Behavior 行为类的定义方式如下:

namespace HomeBehavior;
//**3.2.1版本**开始,行为类的定义无需继承ThinkBehavior类
use ThinkBehavior; 
//**3.2.1版本**开始,行为类的定义无需继承ThinkBehavior类
class TestBehavior extends Behavior {
 //行为扩展的执行入口必须是run
//run方法的参数只允许一个,但可以传入数组。
 public function run(&$params){
 if(C('TEST_PARAM')) {
     echo 'RUNTEST BEHAVIOR '.$params;}
 }
}

行为绑定

行为定义完成后,就需要绑定到某个标签位置才能生效,否则是不会执行的。
我们需要在应用的行为定义文件tags.php
文件中进行行为和标签的位置定义,格式如下:

return array(
 '标签名称1'=>array('行为名1','行为名2',...), 
 '标签名称2'=>array('行为名1','行为名2',...), 
 );

单独执行

行为的调用不一定要放到标签才能调用,如果需要的话,我们可以在控制器中或者其他地方直接调用行为。例如,我们可以把用户权限检测封装成一个行为类,例如:

namespace HomeBehavior;
use ThinkBehavior;
class AuthCheckBehavior extends Behavior {
 // 行为扩展的执行入口必须是run
 public function run(&$return){
 if(C('USER_AUTH_ON')) {
 // 进行权限认证逻辑 如果认证通过 $return = true;
 // 否则用halt输出错误信息
 }
 }
}

定义了AuthCheck行为后,我们可以在控制器的_initialize方法中直接用下面的方式调用:

B('HomeBehaviorAuthCheck');

Apache2 配置

A. Directory Indexes (from mod_autoindex.c)

When you access a directory and there is no default file found in this directory AND Apache Options Indexes is not enabled for this directory.

A.1. DirectoryIndex option example

DirectoryIndex index.html default.php welcome.php

A.2. Options Indexes option

If set, apache will list the directory content if no default file found (from the above  option)

If none of the conditions above is satisfied

You will receive a 403 Forbidden

Recommendations

  • You should not allow directory listing unless REALLY needed.
  • Restrict the default index DirectoryIndex to the minimum.
  • If you want to modify, restrict the modification to the needed directory ONLY, for instance, use .htaccess files, or put your modification inside the <Directory /my/directory> directive

B. Deny, Allow directives (Apache 2.2)

Mentioned by @Radu, @Simon A. Eugster in the comments You request is denied, blacklisted or whitelisted by those directives.

I will not post a full explanation, but I think some examples may help you understand, in short remember this rule:

IF MATCHED BY BOTH, THE LAST IS WILL WIN

Order Allow, Deny

Deny will win if matched by both directives (even if an Allow directive is written after the Deny in the conf)

Order Deny, Allow

Allow will win if matched by both directives

Example 1

Order Allow, Deny
Allow from localhost mydomain.com

Only localhost and *.mydomain.com can access this, all other hosts are denied

Example 2

Order Allow, Deny
Deny from evil.com
Allow from safe.evil.com # <-- has no effect since this will be evaluated first

All requests are denied, the last line may trick you, but remember that if matched by both the last win rule (here Deny is the last), same as written:

Order Allow, Deny
Allow from safe.evil.com
Deny from evil.com # <-- will override the previous one 

Example 4

Order Deny, Allow
Allow from site.com
Deny from untrusted.site.com # <-- has no effect since this will be matched by the above `Allow` directive

Requests are accepted from all hosts

Example 4: typical for public sites (allow unless blacklisted)

Order Allow, Deny
Allow from all
Deny from hacker1.com
Deny from hacker2.com

Example 5: typical for intranet and secure sites (deny unless whitelisted)

Order Deny, Allow
Deny from all
Allow from mypc.localdomain
Allow from managment.localdomain

C. Require directive (Apache 2.4)

Apache 2.4 use a new module called mod_authz_host

Require all granted => Allow all requests

Require all denied => Deny all requests

Require host safe.com => Only from safe.com are allowed


D. Files permissions

One thing that most people do it wrong is configuring files permissions,

The GOLDEN RULE is

STARTS WITH NO PERMISSION AND ADD AS PER YOUR NEED

In linux:

  • Directories should have the Execute permission
  • Files should have the Read permission
  • YES, you are right DO NOT ADD Execute permission for files

for instance, I use this script to setup the folders permissions

# setting permissions for /var/www/mysite.com

# read permission ONLY for the owner 
chmod -R /var/www/mysite.com 400 

# add execute for folders only
find /var/www/mysite.com -type d --exec chmod -R u+x {};

# allow file uploads 
chmod -R /var/www/mysite.com/public/uploads u+w

# allow log writing to this folder
chmod -R /var/www/mysite.com/logs/ 

 

iptables配置示例

#!/bin/bash
# A simple iptables firewall configuration

PATH=/sbin:/bin:/usr/sbin:/usr/bin; export PATH

#flush/erase original rules
iptables -F #清除所有已制定的rule
iptables -X #清除用户自定义的chain/table
iptables -Z #将所有的chain的计数和流量统计归零

#Accept localhost connetting, no matter what it is
iptables -A INPUT -i lo -j ACCEPT

#Accept any response package which is initiated from inside
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#block most common network attacks(recon packets and syn-flood attack)
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

#open ports for different services
iptables -A INPUT -p tcp --dport 22 -j ACCEPT #SSH
iptables -A INPUT -p tcp --dport 80 -j ACCEPT #HTTP
#iptables -A INPUT -p tcp --dport 443 -j ACCEPT #HTTPS
#iptables -A INPUT -p tcp --dport 25 -j ACCEPT #SMTP
#iptables -A INPUT -p tcp --dport 465 -j ACCEPT #Secure SMTP
#iptables -A INPUT -p tcp --dport 110 -j ACCEPT #POP3
#iptables -A INPUT -p tcp --dport 995 -j ACCEPT #Secure POP

#ICMP configuration
#To prevent ICMP DDOS,we do not allow ICMP type 8(echo-request) or limit this request with 1/second
#some ICMP requests are allowed.
icmp_type="0 3 4 11 12 14 16 18"
for ticmp in $icmp_type
do
    iptables -A INPUT -p icmp --icmp-type $ticmp -j ACCEPT
done
#iptables -A INPUT -p icmp --icmp-type 8 -m limit --limit 1/second -j ACCEPT

#default policies
iptables -P OUTPUT ACCEPT
iptables -P INPUT DROP

#save to /etc/sysconfig/iptables
/etc/init.d/iptables save

常用查看Linux系统信息命令

系统

# uname -a               # 查看内核/操作系统/CPU信息
# head -n 1 /etc/issue   # 查看操作系统版本
# cat /proc/cpuinfo      # 查看CPU信息
# hostname               # 查看计算机名
# lspci -tv              # 列出所有PCI设备
# lsusb -tv              # 列出所有USB设备
# lsmod                  # 列出加载的内核模块
# env

# 查看环境变量
资源

# free -m                # 查看内存使用量和交换区使用量
# df -h                  # 查看各分区使用情况
# du -sh <目录名>        # 查看指定目录的大小
# grep MemTotal /proc/meminfo   # 查看内存总量
# grep MemFree /proc/meminfo    # 查看空闲内存量
# uptime                 # 查看系统运行时间、用户数、负载
# cat /proc/loadavg      # 查看系统负载

磁盘和分区

# mount | column -t      # 查看挂接的分区状态
# fdisk -l               # 查看所有分区
# swapon -s              # 查看所有交换分区
# hdparm -i /dev/hda     # 查看磁盘参数(仅适用于IDE设备)
# dmesg | grep IDE       # 查看启动时IDE设备检测状况

网络

# ifconfig               # 查看所有网络接口的属性
# iptables -L            # 查看防火墙设置
# route -n               # 查看路由表
# netstat -lntp          # 查看所有监听端口
# netstat -antp          # 查看所有已经建立的连接
# netstat -s             # 查看网络统计信息

进程

# ps -ef                 # 查看所有进程
# top                    # 实时显示进程状态

用户

# w                      # 查看活动用户
# id <用户名>            # 查看指定用户信息
# last                   # 查看用户登录日志
# cut -d: -f1 /etc/passwd   # 查看系统所有用户
# cut -d: -f1 /etc/group    # 查看系统所有组
# crontab -l             # 查看当前用户的计划任务

服务

# chkconfig --list       # 列出所有系统服务
# chkconfig --list | grep on    # 列出所有启动的系统服务

程序

# rpm -qa                # 查看所有安装的软件包

配置虚拟机LVM

1 为虚拟机新加一块disk,用fdisk把它分成lvm的分区。

root@localhost:~# fdisk /dev/xvdb 
Command (m for help): m
Command action
   a   toggle a bootable flag
   b   edit bsd disklabel
   c   toggle the dos compatibility flag
   d   delete a partition
   l   list known partition types
   m   print this menu
   n   add a new partition
   o   create a new empty DOS partition table
   p   print the partition table
   q   quit without saving changes
   s   create a new empty Sun disklabel
   t   change a partition's system id
   u   change display/entry units
   v   verify the partition table
   w   write table to disk and exit
   x   extra functionality (experts only)

2 显示当前的分区表

Command (m for help): p 

Disk /dev/xvdb: 107.4 GB, 107374182400 bytes
255 heads, 63 sectors/track, 13054 cylinders, total 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xdd2fff2e

    Device Boot      Start         End      Blocks   Id  System
#创建一个新的分区

Command (m for help): n
Partition type:
   p   primary (0 primary, 0 extended, 4 free)
   e   extended

#创建一个主分区
Select (default p): 
Using default response p

#按提示来,用默认值
Partition number (1-4, default 1): 
Using default value 1

#按提示来,用默认值
First sector (2048-209715199, default 2048): 
Using default value 2048

#这里把整个盘分成了一个区
Last sector, +sectors or +size{K,M,G} (2048-209715199, default 209715199): 
Using default value 209715199


# 把分区类型转成lvm
Command (m for help): t
Selected partition 1

#如果不记得分区的类型的代码了,可以用L命令显示分区类型列表
Hex code (type L to list codes): L

 0  Empty           24  NEC DOS         81  Minix / old Lin bf  Solaris        
 1  FAT12           27  Hidden NTFS Win 82  Linux swap / So c1  DRDOS/sec (FAT-
 2  XENIX root      39  Plan 9          83  Linux           c4  DRDOS/sec (FAT-
 3  XENIX usr       3c  PartitionMagic  84  OS/2 hidden C:  c6  DRDOS/sec (FAT-
 4  FAT16 <32M      40  Venix 80286     85  Linux extended  c7  Syrinx         
 5  Extended        41  PPC PReP Boot   86  NTFS volume set da  Non-FS data    
 6  FAT16           42  SFS             87  NTFS volume set db  CP/M / CTOS / .
 7  HPFS/NTFS/exFAT 4d  QNX4.x          88  Linux plaintext de  Dell Utility   
 8  AIX             4e  QNX4.x 2nd part 8e  Linux LVM       df  BootIt         
 9  AIX bootable    4f  QNX4.x 3rd part 93  Amoeba          e1  DOS access     
 a  OS/2 Boot Manag 50  OnTrack DM      94  Amoeba BBT      e3  DOS R/O        
 b  W95 FAT32       51  OnTrack DM6 Aux 9f  BSD/OS          e4  SpeedStor      
 c  W95 FAT32 (LBA) 52  CP/M            a0  IBM Thinkpad hi eb  BeOS fs        
 e  W95 FAT16 (LBA) 53  OnTrack DM6 Aux a5  FreeBSD         ee  GPT            
 f  W95 Ext'd (LBA) 54  OnTrackDM6      a6  OpenBSD         ef  EFI (FAT-12/16/
10  OPUS            55  EZ-Drive        a7  NeXTSTEP        f0  Linux/PA-RISC b
11  Hidden FAT12    56  Golden Bow      a8  Darwin UFS      f1  SpeedStor      
12  Compaq diagnost 5c  Priam Edisk     a9  NetBSD          f4  SpeedStor      
14  Hidden FAT16 <3 61  SpeedStor       ab  Darwin boot     f2  DOS secondary  
16  Hidden FAT16    63  GNU HURD or Sys af  HFS / HFS+      fb  VMware VMFS    
17  Hidden HPFS/NTF 64  Novell Netware  b7  BSDI fs         fc  VMware VMKCORE 
18  AST SmartSleep  65  Novell Netware  b8  BSDI swap       fd  Linux raid auto
1b  Hidden W95 FAT3 70  DiskSecure Mult bb  Boot Wizard hid fe  LANstep        
1c  Hidden W95 FAT3 75  PC/IX           be  Solaris boot    ff  BBT            
1e  Hidden W95 FAT1 80  Old Minix      
Hex code (type L to list codes): 8e
Changed system type of partition 1 to 8e (Linux LVM)

#再看一下

Command (m for help): p

Disk /dev/xvdb: 107.4 GB, 107374182400 bytes
255 heads, 63 sectors/track, 13054 cylinders, total 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xdd2fff2e

    Device Boot      Start         End      Blocks   Id  System
/dev/xvdb1            2048   209715199   104856576   8e  Linux LVM

#写入分区信息

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

#重新加载分区信息

root@localhost:~# partprobe 
root@localhost:~# fdisk -l

Disk /dev/xvda: 32.2 GB, 32212254720 bytes
255 heads, 63 sectors/track, 3916 cylinders, total 62914560 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00020a62

    Device Boot      Start         End      Blocks   Id  System
/dev/xvda1            2048      499711      248832   83  Linux
/dev/xvda2          501758    62912511    31205377    5  Extended
/dev/xvda5          501760    62912511    31205376   8e  Linux LVM

Disk /dev/xvdb: 107.4 GB, 107374182400 bytes
43 heads, 44 sectors/track, 110843 cylinders, total 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xdd2fff2e
#这是我们刚创建的lvm分区
    Device Boot      Start         End      Blocks   Id  System
/dev/xvdb1            2048   209715199   104856576   8e  Linux LVM

Disk /dev/mapper/localhost--vg-root: 30.6 GB, 30614224896 bytes
255 heads, 63 sectors/track, 3721 cylinders, total 59793408 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/localhost--vg-root doesn't contain a valid partition table

Disk /dev/mapper/localhost--vg-swap_1: 1337 MB, 1337982976 bytes
255 heads, 63 sectors/track, 162 cylinders, total 2613248 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/localhost--vg-swap_1 doesn't contain a valid partition table

#创建一个lvm物理卷pv

root@localhost:~# pvcreate /dev/xvdb1
  Physical volume "/dev/xvdb1" successfully created
  
root@localhost:~# pvscan
  PV /dev/xvda5   VG localhost-vg    lvm2 [29.76 GiB / 0    free]
  PV /dev/xvdb1                      lvm2 [100.00 GiB]
  Total: 2 [129.76 GiB] / in use: 1 [29.76 GiB] / in no VG: 1 [100.00 GiB]

#因为我们在安装ubuntu时选择lvm类型,所以已经有了vg了。

root@localhost:~# vgscan
  Reading all physical volumes.  This may take a while...
  Found volume group "localhost-vg" using metadata type lvm2

#把新建的pv添加到vg里吧

root@localhost:~# vgextend localhost-vg /dev/xvdb1
  Volume group "localhost-vg" successfully extended

#看一下vg的详情

root@localhost:~# vgdisplay 
  --- Volume group ---
  VG Name               localhost-vg
  System ID             
  Format                lvm2
  Metadata Areas        2
  Metadata Sequence No  4
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                2
  Act PV                2
  VG Size               129.75 GiB
  PE Size               4.00 MiB
  Total PE              33217
  Alloc PE / Size       7618 / 29.76 GiB
  Free  PE / Size       25599 / 100.00 GiB  <= 这个信息很重要,我们在扩大lv时要用到
  VG UUID               B1b5mq-JMhc-HbPo-ImdF-50pB-fpML-eivSLF

#看看系统里的逻辑卷lv吧

root@localhost:~# lvdisplay 
  --- Logical volume ---
  LV Path                /dev/localhost-vg/root
  LV Name                root
  VG Name                localhost-vg
  LV UUID                YfzzNm-ozhH-k2r2-KucH-p2he-CcVj-SCpuAr
  LV Write Access        read/write
  LV Creation host, time localhost, 2015-01-26 16:36:55 +0800
  LV Status              available
  # open                 1
  LV Size                28.51 GiB  <= 大小还没变
  Current LE             7299
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:0
   
  --- Logical volume ---
  LV Path                /dev/localhost-vg/swap_1
  LV Name                swap_1
  VG Name                localhost-vg
  LV UUID                6Kid6V-tQ1B-TT43-g7at-Ha1d-yR3X-DomZA7
  LV Write Access        read/write
  LV Creation host, time localhost, 2015-01-26 16:36:55 +0800
  LV Status              available
  # open                 2
  LV Size                1.25 GiB
  Current LE             319
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:1

#扩大lv的容量,加号后面的值要是vgdisplay命令输出里的Free PE / Size 25599 / 100.00 GiB 这个值,当然可以小于这个值,也就是不全部分配给这个lv.

root@localhost:~# lvresize -l +25599 /dev/localhost-vg/root
  Extending logical volume root to 128.51 GiB
  Logical volume root successfully resized

#再看看vg,会发现Free PE数量为0了。

root@localhost:~# vgdisplay
  --- Volume group ---
  VG Name               localhost-vg
  System ID             
  Format                lvm2
  Metadata Areas        2
  Metadata Sequence No  5
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                2
  Act PV                2
  VG Size               129.75 GiB
  PE Size               4.00 MiB
  Total PE              33217
  Alloc PE / Size       33217 / 129.75 GiB
  Free  PE / Size       0 / 0   
  VG UUID               B1b5mq-JMhc-HbPo-ImdF-50pB-fpML-eivSLF

#df一下看看。

root@localhost:~# df -h
Filesystem                      Size  Used Avail Use% Mounted on
/dev/mapper/localhost--vg-root   28G  1.3G   26G   5% /
none                            4.0K     0  4.0K   0% /sys/fs/cgroup
udev                            4.8G  4.0K  4.8G   1% /dev
tmpfs                           979M  400K  978M   1% /run
none                            5.0M     0  5.0M   0% /run/lock
none                            4.8G     0  4.8G   0% /run/shm
none                            100M     0  100M   0% /run/user
/dev/xvda1                      236M   37M  187M  17% /boot

#What!为什么这里的容量还不对?因为你只是调整了lv的大小,它上面的文件系统还不知道呢。
#好吧,我们来把lv的容量扩到文件系统里吧。

  
root@localhost:~# resize2fs /dev/mapper/localhost--vg-root 
resize2fs 1.42.9 (4-Feb-2014)
Filesystem at /dev/mapper/localhost--vg-root is mounted on /; on-line resizing required
old_desc_blocks = 2, new_desc_blocks = 9
The filesystem on /dev/mapper/localhost--vg-root is now 33687552 blocks long.

#再看看吧,OK!

root@localhost:~# df -h
Filesystem                      Size  Used Avail Use% Mounted on
/dev/mapper/localhost--vg-root  127G  1.3G  120G   2% /
none                            4.0K     0  4.0K   0% /sys/fs/cgroup
udev                            4.8G  4.0K  4.8G   1% /dev
tmpfs                           979M  400K  978M   1% /run
none                            5.0M     0  5.0M   0% /run/lock
none                            4.8G     0  4.8G   0% /run/shm
none                            100M     0  100M   0% /run/user
/dev/xvda1                      236M   37M  187M  17% /boot