Centos7下使用Ceph-deploy快速部署Ceph分布式存储

#Centos7下使用Ceph-deploy快速部署Ceph分布式存储

CEPH 简介
 不管你是想为云平台提供Ceph 对象存储和/或 Ceph 块设备,还是想部署一个 Ceph 文件系统或者把 Ceph 作为他用,所有 Ceph 存储集群的部署都始于部署一个个 Ceph 节点、网络和 Ceph 存储集群。
 Ceph 存储集群至少需要一个 Ceph Monitor 和两个 OSD 守护进程。而运行 Ceph 文件系统客户端时,则必须要有元数据服务器( Metadata Server )。
 
•    Ceph OSDs: Ceph OSD 守护进程( Ceph OSD )的功能是存储数据,处理数据的复制、恢复、回填、再均衡,并通过检查其他OSD 守护进程的心跳来向 Ceph Monitors 提供一些监控信息。
    当 Ceph 存储集群设定为有2个副本时,至少需要2个 OSD 守护进程,集群才能达到 active+clean 状态( Ceph 默认有3个副本,但你可以调整副本数)。
•    Monitors: Ceph Monitor维护着展示集群状态的各种图表,包括监视器图、 OSD 图、归置组( PG )图、和 CRUSH 图。 Ceph 保存着发生在Monitors 、 OSD 和 PG上的每一次状态变更的历史信息(称为 epoch )。
•    MDSs: Ceph 元数据服务器( MDS )为 Ceph 文件系统存储元数据(也就是说,Ceph 块设备和 Ceph 对象存储不使用MDS )。元数据服务器使得 POSIX 文件系统的用户们,可以在不对 Ceph 存储集群造成负担的前提下,
    执行诸如 ls、find 等基本命令。Ceph 把客户端数据保存为存储池内的对象。通过使用 CRUSH 算法, Ceph 可以计算出哪个归置组(PG)应该持有指定的对象(Object),然后进一步计算出哪个 OSD 守护进程持有该归置组。
    CRUSH 算法使得 Ceph 存储集群能够动态地伸缩、再均衡和修复。

 Ceph 把客户端数据保存为存储池内的对象。通过使用 CRUSH 算法, Ceph 可以计算出哪个归置组(PG)应该持有指定的对象(Object),然后进一步计算出哪个 OSD 守护进程持有该归置组。
 CRUSH 算法使得 Ceph 存储集群能够动态地伸缩、再均衡和修复。
 
###Centos7使用Ceph-deploy快速部署Ceph环境:
----
###1)基本环境

    172.16.1.205    ceph-001(ceph-deploy)   mds、mon、osd1(元数据服务,MDS;监视器,MON;也可以将mon、mds节点另放一台机器)RGW(Ceph对象网关)
    172.16.1.206    ceph-002                  osd2  
    172.16.1.207    ceph-003                  osd3
    172.16.1.208    ceph-client               client(CEPH客户端)                      

####初始化
yum -y install wget net-tools lrzsz gcc gcc-c++ make cmake libxml2-devel openssl-devel curl curl-devel unzip sudo ntp libaio-devel vim ncurses-devel autoconf automake zlib-devel python-devel iftop htop iotop sysstat lsof telnet traceroute tree man yum-plugin-priorities
yum -y install epel-release    
----
####每个节点修改主机名
    hostnamectl set-hostname ceph-001
    hostnamectl set-hostname ceph-002
    hostnamectl set-hostname ceph-003    
    hostnamectl set-hostname ceph-client
----

####每个节点绑定主机名映射
cat /etc/hosts
172.16.1.205    ceph-001
172.16.1.206    ceph-002
172.16.1.207    ceph-003
172.16.1.208    ceph-client
----
####每个节点确认连通性
    ping -c 3 ceph-001
    ping -c 3 ceph-002
    ping -c 3 ceph-003
    ping -c 3 ceph-client
####账户密码
172.16.1.205
root/123456
ceph/ceph

----
####每个节点关闭防火墙和selinux
    systemctl stop firewalld
    systemctl disable firewalld
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
    setenforce 0
----
####每个节点安装和配置NTP(官方推荐的是集群的所有节点全部安装并配置 NTP,需要保证各节点的系统时间一致。没有自己部署ntp服务器,就在线同步NTP)
    sudo yum install ntp ntpdate ntp-doc -y
    sudo systemctl restart ntpd
    sudo systemctl status ntpd
    sudo systemctl enable ntpd
-------------------------------------------------
####每个节点准备yum源
    删除默认的源,国外的比较慢
    yum clean all
    mkdir -p /etc/yum.repos.d/bak
    mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak/
     
    下载阿里云的base源和epel源
    wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
    yum clean all && yum makecache
    sudo yum -y install yum-plugin-priorities
    
####添加ceph源

# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo  

#MIMIC版V13.2.6 阿里源
# sudo vim /etc/yum.repos.d/ceph.repo  
                                                
[Ceph]
name=Ceph packages for $basearch
baseurl=https://mirrors.aliyun.com/ceph/rpm-mimic/el7/$basearch
enabled=1
gpgcheck=1
priority=1
gpgkey=https://mirrors.aliyun.com/ceph/keys/release.asc
[Ceph-noarch]
name=Ceph noarch packages
baseurl=https://mirrors.aliyun.com/ceph/rpm-mimic/el7/noarch
enabled=1
gpgcheck=1
priority=1
gpgkey=https://mirrors.aliyun.com/ceph/keys/release.asc
[ceph-source]
name=Ceph source packages
baseurl=https://mirrors.aliyun.com/ceph/rpm-mimic/el7/SRPMS
enabled=1
gpgcheck=1
priority=1
gpgkey=https://mirrors.aliyun.com/ceph/keys/release.asc


####官方源
[Ceph]
name=Ceph packages for $basearch
baseurl=http://download.ceph.com/rpm-mimic/el7/$basearch
enabled=1
gpgcheck=1
type=rpm-md
gpgkey=https://download.ceph.com/keys/release.asc
priority=1

[Ceph-noarch]
name=Ceph noarch packages
baseurl=http://download.ceph.com/rpm-mimic/el7/noarch
enabled=1
gpgcheck=1
type=rpm-md
gpgkey=https://download.ceph.com/keys/release.asc
priority=1

[ceph-source]
name=Ceph source packages
baseurl=http://download.ceph.com/rpm-mimic/el7/SRPMS
enabled=1
gpgcheck=1
type=rpm-md
gpgkey=https://download.ceph.com/keys/release.asc
priority=1

####每个节点创建ceph用户,设置sudo权限
    useradd -d /home/ceph -m ceph
    echo "ceph"|passwd --stdin ceph
    echo "ceph ALL = (root) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/ceph
    chmod 0440 /etc/sudoers.d/ceph
    sed -i s'/Defaults requiretty/Defaults requiretty'/g /etc/sudoers
 
####测试ceph的sudo权限
    su - ceph
    $ sudo su -

----

####配置相互间的ssh信任关系
    现在ceph-admin节点上产生公私钥文件,然后将ceph-admin节点的.ssh目录拷贝给其他节点
    [root@ceph-001 ~]su ceph
    [ceph@ceph-001 ~]$ ssh-keygen -t rsa    一路回车
    [ceph@ceph-001 ~]$ cd .ssh/
    [ceph@ceph-001 .ssh]$ ls
    id_rsa  id_rsa.pub
    [ceph@ceph-001 .ssh]$ cp id_rsa.pub authorized_keys 
    [ceph@ceph-001 .ssh]$ scp -r /home/ceph/.ssh ceph-001:/home/ceph/
    [ceph@ceph-001 .ssh]$ scp -r /home/ceph/.ssh ceph-002:/home/ceph/
    [ceph@ceph-001 .ssh]$ scp -r /home/ceph/.ssh ceph-003:/home/ceph/
     
    然后在各节点直接验证ceph用户下的ssh相互信任关系
    $ ssh -p22 ceph@ceph-001
    $ ssh -p22 ceph@ceph-002
    $ ssh -p22 ceph@ceph-003

###2)准备磁盘(ceph-001、ceph-002、ceph-003三个节点)

    测试时使用的磁盘不要太小,否则后面添加磁盘时会报错,建议磁盘大小为20G及以上。
    
    如下分别在三个节点挂载了一块100G的裸盘
     
    检查磁盘
    $ sudo fdisk -l /dev/sdb
    Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 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
     
    格式化磁盘
    $ sudo parted -s /dev/sdb mklabel gpt mkpart primary xfs 0% 100%
    $ sudo mkfs.xfs /dev/sdb -f
     
    查看磁盘格式(xfs格式)
    $ sudo blkid -o value -s TYPE /dev/sdb
    
    今天在centos下用xfs格式化磁盘出现如下错误
    mkfs.xfs -f /dev/sdb
    时出现:
    mkfs.xfs: cannot open /dev/sdb: Device or resource busy
    重启服务器后再格式化也一样,也就是重启服务器没什么用。
    用lsof查看是谁在占用,也没什么效果。

    解决方法:
    [root@ceph-001 ~]# dmsetup ls
    ceph--b06e3709--9991--4ab9--94a6--cbf88d3b20e1-osd--block--a62a976e--764f--48ba--bf27--fb467f8cd608    (253:0)
    然后我们移除这个占用
    [root@xiaohuai]# dmsetup remove ceph--b06e3709--9991--4ab9--94a6--cbf88d3b20e1-osd--block--a62a976e--764f--48ba--bf27--fb467f8cd608
    
###3)部署阶段(ceph-admin节点上使用ceph-deploy快速部署)

[root@ceph-001 ~]su - ceph
      
####安装ceph-deploy
[ceph@ceph-001 ~]$ sudo yum update -y && sudo yum install ceph-deploy -y
      
####创建cluster目录
[ceph@ceph-001 ~]$ mkdir cluster
[ceph@ceph-001 ~]$ cd cluster/

[ceph@ceph-001 ~]$ sudo yum install python2-pip* -y
      
####创建集群(后面填写monit节点的主机名,这里monit节点和管理节点是同一台机器,即ceph-admin)
    [ceph@ceph-001 cluster]$ ceph-deploy new ceph-001 ceph-002 ceph-003
    
    [ceph_deploy.conf][DEBUG ] found configuration file at: /home/ceph/.cephdeploy.conf
    [ceph_deploy.cli][INFO  ] Invoked (1.5.39): /bin/ceph-deploy new ceph-001
    [ceph_deploy.cli][INFO  ] ceph-deploy options:
    [ceph_deploy.cli][INFO  ]  username                      : None
    [ceph_deploy.cli][INFO  ]  func                          : <function new at 0x7fe090f625f0>
    [ceph_deploy.cli][INFO  ]  verbose                       : False
    [ceph_deploy.cli][INFO  ]  overwrite_conf                : False
    [ceph_deploy.cli][INFO  ]  quiet                         : False
    [ceph_deploy.cli][INFO  ]  cd_conf                       : <ceph_deploy.conf.cephdeploy.Conf instance at 0x7fe0906d7d88>
    [ceph_deploy.cli][INFO  ]  cluster                       : ceph
    [ceph_deploy.cli][INFO  ]  ssh_copykey                   : True
    [ceph_deploy.cli][INFO  ]  mon                           : ['ceph-001']
    [ceph_deploy.cli][INFO  ]  public_network                : None
    [ceph_deploy.cli][INFO  ]  ceph_conf                     : None
    [ceph_deploy.cli][INFO  ]  cluster_network               : None
    [ceph_deploy.cli][INFO  ]  default_release               : False
    [ceph_deploy.cli][INFO  ]  fsid                          : None
    [ceph_deploy.new][DEBUG ] Creating new cluster named ceph
    [ceph_deploy.new][INFO  ] making sure passwordless SSH succeeds
    [ceph-001][DEBUG ] connection detected need for sudo
    [ceph-001][DEBUG ] connected to host: ceph-001 
    [ceph-001][DEBUG ] detect platform information from remote host
    [ceph-001][DEBUG ] detect machine type
    [ceph-001][DEBUG ] find the location of an executable
    [ceph-001][INFO  ] Running command: sudo /usr/sbin/ip link show
    [ceph-001][INFO  ] Running command: sudo /usr/sbin/ip addr show
    [ceph-001][DEBUG ] IP addresses found: [u'172.16.1.205']
    [ceph_deploy.new][DEBUG ] Resolving host ceph-001
    [ceph_deploy.new][DEBUG ] Monitor ceph-001 at 172.16.1.205
    [ceph_deploy.new][DEBUG ] Monitor initial members are ['ceph-001']
    [ceph_deploy.new][DEBUG ] Monitor addrs are ['172.16.1.205']
    [ceph_deploy.new][DEBUG ] Creating a random mon key...
    [ceph_deploy.new][DEBUG ] Writing monitor keyring to ceph.mon.keyring...
    [ceph_deploy.new][DEBUG ] Writing initial config to ceph.conf...

####修改ceph.conf文件(注意:mon_host必须和public network 网络是同网段内!)

[ceph@ceph-001 cluster]$ vim ceph.conf     #添加下面两行配置内容

public network = 172.16.1.0/24
osd pool default size = 2                 #副本数(默认3个)
osd pool default min size = 1
osd pool default pg num = 32
osd pool default pgp num = 32
      
####安装ceph(过程有点长,需要等待一段时间....)
[ceph@ceph-001 cluster]$ ceph-deploy install ceph-001 ceph-002 ceph-003
 或
 sudo yum -y install ceph ceph-radosgw
 
####配置初始monitor、并收集所有密钥 
####初始化Monitor监视器节点,并收集所有密钥
    [ceph@ceph-001 cluster]$ ceph-deploy mon create-initial
///    [ceph@ceph-001 cluster]$ ceph-deploy gatherkeys ceph-001

    [ceph@ceph-001 cluster]$sudo systemctl enable ceph-mon@ceph-001
    [ceph@ceph-001 cluster]$sudo systemctl start ceph-mon@ceph-001
    
####分发配置文件     
####用ceph-deploy把配置文件和admin密钥拷贝到管理节点和Ceph节点(这样你每次执行Ceph命令行时就无需指定monit节点地址和ceph.client.admin.keyring了)
    [ceph@ceph-001 cluster]$ ceph-deploy admin ceph-001 ceph-002 ceph-003
               
####配置mgr    
####自从ceph 12版本开始,manager是必须的,应该为每个运行monitor的机器添加一个mgr,否则集群处于WARN状态。
####mimic 版 dashboard 安装
1、添加mgr 功能
[ceph@ceph-001 cluster]$ ceph-deploy mgr create ceph-001 ceph-002 ceph-003

2、开启dashboard 功能
[ceph@ceph-001 cluster]$ ceph mgr module enable dashboard

3、创建证书
[ceph@ceph-001 cluster]$ ceph dashboard create-self-signed-cert

$ openssl req -new -nodes -x509 \
  -subj "/O=IT/CN=ceph-mgr-dashboard" -days 3650 \
  -keyout dashboard.key -out dashboard.crt -extensions v3_ca

$ ceph dashboard set-ssl-certificate -i dashboard.crt
$ ceph dashboard set-ssl-certificate-key -i dashboard.key
设置禁用SSL
$ ceph config set mgr mgr/dashboard/ssl false

$ ceph mgr module disable dashboard
$ ceph mgr module enable dashboard

4、创建 web 登录用户密码(设置登录凭证)
[ceph@ceph-001 cluster]$ ceph dashboard set-login-credentials guiji 123456

创建具有管理员角色的用户:

$ ceph dashboard ac-user-create <username> <password> administrator

5、查看服务访问方式
[ceph@ceph-001 cluster]$ ceph mgr services
6、在/etc/ceph/ceph.conf中添加
[mgr]
mgr modules = dashboard

7、设置dashboard的ip和端口
$ ceph config set mgr mgr/dashboard/server_addr 172.16.1.205
$ ceph config set mgr mgr/dashboard/server_port 7000
$ ceph config set mgr mgr/dashboard/ssl_server_port 8443
或者
$ ceph config-key set mgr/dashboard/server_addr 172.16.1.205
$ ceph config-key set mgr/dashboard/server_port 7000


####可以通过ceph mgr dump查看当前集群在使用那几个模块(12的版本支持挺多的模块,比如:dashboard,prometheus,restful,status,zabbix")
[ceph@ceph-001 cluster]$ ceph mgr dump
https://ceph-001:8443/

####也可以通过这个查看当前集群是否支持dashboard
[root@ceph-1 ~]# ceph mgr module ls

####设置dashboard访问地址和端口
ceph config-key set mgr/dashboard/server_addr 172.16.1.205          ////// server_addr为有ceph-mgr进程的那台机器的ip地址
ceph config-key set mgr/dashboard/server_port 7000                  /////server_port可以随意设。这里也7000为例
 
####查看配置的状态和参数和怎么删除上面设置
[root@ceph-1 ceph-ceph-1]# ceph config-key dump                     /////查看配置的状态      
{
    "mgr/dashboard/server_addr": "172.16.1.205",
    "mgr/dashboard/server_port": "7000"
}
[root@ceph-1 ceph-ceph-1]# ceph config-key del mgr/dashboard/server_addr    ////删除配置的参数

###查看端口是否设置成功

[root@ceph-1 ~]# netstat -tunlp|grep ceph-mgr|grep LISTEN
tcp        0      0 0.0.0.0:6804            0.0.0.0:*               LISTEN      9128/ceph-mgr       
tcp        0      0 172.16.1.205:7000        0.0.0.0:*               LISTEN      9128/ceph-mgr   

已经成功设置

设置完之后就重启mgr服务

systemctl restart ceph-mgr@ceph-001

访问dashboard
8、登录:
https://172.16.1.205:7000       /////具体访问地址根据自己的设定地址进行访问

# 提示:当ceph-mgr发生故障,相当于整个ceph集群都会出现严重问题,
# 建议在每个mon中都创建独立的ceph-mgr(至少3个ceph mon节点),只需要在每个mon节点参考上面的方法进行创建即可(每个mgr需要不同的独立命名)。 

# 关闭ceph-mgr的方式
shell> systemctl stop ceph-mgr@ceph-001

###配置osd节点 
###添加OSD到集群
####检查OSD节点上所有可用的磁盘
[ceph@ceph-001 cluster]$ ceph-deploy disk list ceph-001 ceph-002 ceph-003

ceph-deploy osd create --data /dev/sdb ceph-001
ceph-deploy osd create --data /dev/sdb ceph-002
ceph-deploy osd create --data /dev/sdb ceph-003
      
####使用zap选项删除所有osd节点上的分区
ceph-deploy disk zap {osd-server-name}:{disk-name}
ceph-deploy disk zap osdserver1:sdb
[ceph@ceph-001 cluster]$ ceph-deploy disk zap ceph-001:/dev/sdb
[ceph@ceph-001 cluster]$ ceph-deploy disk zap ceph-002:/dev/sdb
[ceph@ceph-001 cluster]$ ceph-deploy disk zap ceph-003:/dev/sdb
   
####准备OSD(使用prepare命令)
[ceph@ceph-001 cluster]$ ceph-deploy osd prepare ceph-001:/dev/sdb ceph-002:/dev/sdb ceph-003:/dev/sdb
      
####激活OSD(注意由于ceph对磁盘进行了分区,/dev/sdb磁盘分区为/dev/sdb1)
ceph-deploy osd activate {node-name}:{data-disk-partition}[:{journal-disk-partition}]
ceph-deploy osd activate osdserver1:/dev/sdb1:/dev/ssd1
ceph-deploy osd activate osdserver1:/dev/sdc1:/dev/ssd2
[ceph@ceph-001 cluster]$ ceph-deploy osd activate ceph-001:/dev/sdb1
[ceph@ceph-001 cluster]$ ceph-deploy osd activate ceph-002:/dev/sdb1
[ceph@ceph-001 cluster]$ ceph-deploy osd activate ceph-003:/dev/sdb1

####可能出现下面的报错:(副本数大于OSD节点数导致)
    [ceph-node1][WARNIN] ceph_disk.main.Error: Error: /dev/sdb1 is not a directory or block device
    [ceph-node1][ERROR ] RuntimeError: command returned non-zero exit status: 1
    [ceph_deploy][ERROR ] RuntimeError: Failed to execute command: /usr/sbin/ceph-disk -v activate --mark-init systemd --mount /dev/sdb1

####在三个osd节点上通过命令已显示磁盘已成功mount:
[ceph@ceph-node01 ~]$ lsblk
    NAME            MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
    sr0              11:0    1  4.2G  0 rom
    vda             252:0    0   70G  0 disk
    ├─vda1          252:1    0    1G  0 part /boot
    └─vda2          252:2    0   69G  0 part
      ├─centos-root 253:0    0 43.8G  0 lvm  /
      ├─centos-swap 253:1    0  3.9G  0 lvm  [SWAP]
      └─centos-home 253:2    0 21.4G  0 lvm  /home
    vdb             252:16   0   20G  0 disk
    ├─vdb1          252:17   0   15G  0 part /var/lib/ceph/osd/ceph-0       挂载成功
    └─vdb2          252:18   0    5G  0 part
         
    [ceph@ceph-node02 ~]$ lsblk
    NAME            MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
    sr0              11:0    1  4.2G  0 rom
    vda             252:0    0   70G  0 disk
    ├─vda1          252:1    0    1G  0 part /boot
    └─vda2          252:2    0   69G  0 part
      ├─centos-root 253:0    0 43.8G  0 lvm  /
      ├─centos-swap 253:1    0  3.9G  0 lvm  [SWAP]
      └─centos-home 253:2    0 21.4G  0 lvm  /home
    vdb             252:16   0   20G  0 disk
    ├─vdb1          252:17   0   15G  0 part /var/lib/ceph/osd/ceph-1        挂载成功
    └─vdb2          252:18   0    5G  0 part
         
    [ceph@ceph-node03 ~]$ lsblk
    NAME            MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
    sr0              11:0    1  4.2G  0 rom
    vda             252:0    0   70G  0 disk
    ├─vda1          252:1    0    1G  0 part /boot
    └─vda2          252:2    0   69G  0 part
      ├─centos-root 253:0    0 43.8G  0 lvm  /
      ├─centos-swap 253:1    0  3.9G  0 lvm  [SWAP]
      └─centos-home 253:2    0 21.4G  0 lvm  /home
    vdb             252:16   0   20G  0 disk
    ├─vdb1          252:17   0   15G  0 part /var/lib/ceph/osd/ceph-2       挂载成功
    └─vdb2          252:18   0    5G  0 part
     
####查看OSD:
    [ceph@ceph-001 cluster]$ ceph-deploy disk list ceph-001 ceph-002 ceph-003
    ........
    [ceph-node1][DEBUG ]  /dev/sdb2 ceph journal, for /dev/sdb1      如下显示这两个分区,则表示成功了
    [ceph-node1][DEBUG ]  /dev/sdb1 ceph data, active, cluster ceph, osd.0, journal /dev/sdb2
    ........
    [ceph-node3][DEBUG ]  /dev/sdb2 ceph journal, for /dev/sdb1       
    [ceph-node3][DEBUG ]  /dev/sdb1 ceph data, active, cluster ceph, osd.1, journal /dev/sdb2
    .......
    [ceph-node3][DEBUG ]  /dev/sdb2 ceph journal, for /dev/sdb1
    [ceph-node3][DEBUG ]  /dev/sdb1 ceph data, active, cluster ceph, osd.2, journal /dev/sdb2
         
     
####用ceph-deploy把配置文件和admin密钥拷贝到管理节点和Ceph节点(这样你每次执行Ceph命令行时就无需指定monit节点地址和ceph.client.admin.keyring了)
    [ceph@ceph-001 cluster]$ ceph-deploy admin ceph-001 ceph-002 ceph-003
         
    修改密钥权限
    [ceph@ceph-001 cluster]$ sudo chmod 644 /etc/ceph/ceph.client.admin.keyring
         
    检查ceph状态
    [ceph@ceph-001 cluster]$ sudo ceph health
    HEALTH_OK
    [ceph@ceph-001 cluster]$ sudo ceph -s
    cluster 33bfa421-8a3b-40fa-9f14-791efca9eb96
    health HEALTH_OK
    monmap e1: 1 mons at {ceph-001=172.16.1.205:6789/0}
          election epoch 3, quorum 0 ceph-001
    osdmap e14: 3 osds: 3 up, 3 in
           flags sortbitwise,require_jewel_osds
    pgmap v29: 64 pgs, 1 pools, 0 bytes data, 0 objects
         100 MB used, 45946 MB / 46046 MB avail
         64 active+clean
    
####查看ceph osd运行状态
[ceph@ceph-001 ~]$ sudo ceph osd stat
     osdmap e19: 3 osds: 3 up, 3 in
            flags sortbitwise,require_jewel_osds
   
####查看osd的目录树
    [ceph@ceph-001 ~]$ sudo ceph osd tree
    ID WEIGHT  TYPE NAME           UP/DOWN REWEIGHT PRIMARY-AFFINITY
    -1 0.04376 root default                                       
    -2 0.01459     host ceph-node1                                
     0 0.01459         osd.0            up  1.00000          1.00000
    -3 0.01459     host ceph-node2                                
     1 0.01459         osd.1            up  1.00000          1.00000
    -4 0.01459     host ceph-node3                                
     2 0.01459         osd.2            up  1.00000          1.00000
   
####查看monit监控节点的服务情况
    [ceph@ceph-001 cluster]$ sudo systemctl status ceph-mon@ceph-001
    [ceph@ceph-001 cluster]$ ps -ef|grep ceph|grep 'cluster'
    ceph     28190     1  0 11:44 ?        00:00:01 /usr/bin/ceph-mon -f --cluster ceph --id ceph-001 --setuser ceph --setgroup ceph
        
    分别查看下ceph-node1、ceph-node2、ceph-node3三个节点的osd服务情况,发现已经在启动中。
    [ceph@ceph-node1 ~]$ sudo systemctl status [email protected]         启动是start、重启是restart
    [ceph@ceph-node1 ~]$ sudo ps -ef|grep ceph|grep "cluster"
    ceph     28749     1  0 11:44 ?        00:00:00 /usr/bin/ceph-osd -f --cluster ceph --id 0 --setuser ceph --setgroup ceph
    ceph 29197 29051  0 11:54 pts/2    00:00:00 grep --color=auto cluster
      
    [ceph@ceph-node2 ~]$ sudo systemctl status [email protected]
    [ceph@ceph-node2 ~]$ sudo ps -ef|grep ceph|grep "cluster"
    ceph     28749     1  0 11:44 ?        00:00:00 /usr/bin/ceph-osd -f --cluster ceph --id 0 --setuser ceph --setgroup ceph
    ceph 29197 29051  0 11:54 pts/2    00:00:00 grep --color=auto cluster
      
    [ceph@ceph-node3 ~]$ sudo systemctl status [email protected]
    [ceph@ceph-node3 ~]$ sudo ps -ef|grep ceph|grep "cluster"
    ceph     28749     1  0 11:44 ?        00:00:00 /usr/bin/ceph-osd -f --cluster ceph --id 0 --setuser ceph --setgroup ceph
    ceph 29197 29051  0 11:54 pts/2    00:00:00 grep --color=auto cluster
    
    
###ceph pool常用命令
注:以下命令在root下运行没有问题,如果ceph集群用非root用户部署,请加sudo

1、创建pool操作:
ceph osd pool create {pool-name} {pg-num} [{pgp-num}] [replicated] \
        [crush-ruleset-name] [expected-num-objects]
ceph osd pool create {pool-name} {pg-num}  {pgp-num}   erasure \
        [erasure-code-profile] [crush-ruleset-name] [expected_num_objects]

 这里强制选择pg_num和pgp_num,因为ceph集群不能自动计算pg数量。下面有一些官方建议的pg使用数量:

小于5个osd设置pg_num为128
5到10个osd设置pg_num为512
10到50个osd设置pg_num为1024
如果超过50个osd你需要自己明白权衡点,并且能自行计算pg_num的数量
      pg_num通用计算方法
                 (OSDs * 100)
   Total PGs =  ------------
                  pool size
                  
$ ceph osd pool create cephfs_data <pg_num>
$ ceph osd pool create cephfs_metadata <pg_num>
注:确定 pg_num 取值是强制性的,因为不能自动计算。下面是几个常用的值:
    少于 5 个 OSD 时可把 pg_num 设置为 128;
    OSD 数量在 5 到 10 个时,可把 pg_num 设置为 512;
    OSD 数量在 10 到 50 个时,可把 pg_num 设置为 4096;
    OSD 数量大于 50 时,你得理解权衡方法、以及如何自己计算 pg_num 取值;
    自己计算 pg_num 取值时可借助 pgcalc 工具。

存储池、归置组和 CRUSH 配置参考¶
当你创建存储池并给它设置归置组数量时,如果你没指定 Ceph 就用默认值。我们建议更改某些默认值,特别是存储池的副本数和默认归置组数量,可以在运行 pool 命令的时候设置这些值。你也可以把配置写入 Ceph 配置文件的 [global] 段来覆盖默认值。

[global]

    # By default, Ceph makes 3 replicas of objects. If you want to make four 
    # copies of an object the default value--a primary copy and three replica 
    # copies--reset the default values as shown in 'osd pool default size'.
    # If you want to allow Ceph to write a lesser number of copies in a degraded 
    # state, set 'osd pool default min size' to a number less than the
    # 'osd pool default size' value.

    osd pool default size = 4  # Write an object 4 times.
    osd pool default min size = 1 # Allow writing one copy in a degraded state.

    # Ensure you have a realistic number of placement groups. We recommend
    # approximately 100 per OSD. E.g., total number of OSDs multiplied by 100 
    # divided by the number of replicas (i.e., osd pool default size). So for
    # 10 OSDs and osd pool default size = 4, we'd recommend approximately
    # (100 * 10) / 4 = 250.

    osd pool default pg num = 250
    osd pool default pgp num = 250
2、在任意节点上查看集群pools:

1)ceph osd lspools

2)rados lspools

3)ceph osd dump | grep -i pool

设置存储池配额
存储池配额可设置最大字节数、和/或每存储池最大对象数。

ceph osd pool set-quota {pool-name} [max_objects {obj-count}] [max_bytes {bytes}]
例如:

ceph osd pool set-quota data max_objects 10000

3、在任意node上删除池

ceph osd pool delete ${poolname} ${poolname} --yes-i-really-really-mean-it

注:这里防止误删,需要输入两次池名,必须使用参数--yes-i-really-really-mean-it

删除 pool先在ceph.conf 增加下面:

mon_allow_pool_delete = true

并重启ceph-mon:

sudo systemctl restart ceph-mon@ceph-001

重命名存储池
要重命名一个存储池,执行:

ceph osd pool rename {current-pool-name} {new-pool-name}

4、修改pool的pg_num,pgp_num

ceph osd pool set ${poolname} pg_num ${pg_num}

ceph osd pool set ${poolname} pgp_num ${pgp_num}

需要注意, pg_num只能增加, 不能缩小.
[ceph@ceph-001 cluster]$ sudo ceph osd pool set cephfs_data pg_num 64
Error EEXIST: specified pg_num 64 <= current 128

注:pg_num=pgp_num,当且仅当修改完pgp_num之后,pool中pg才会有remap,backfill等操作

5、查看pool中所有对象

rados -p ${poolname} ls

注:查看对象所在osd可用命令 :  ceph osd map ${poolname} ${objname}

6、重命名pool

ceph osd pool rename ${poololdname} ${newpoolname}

7、设置pool副本数

ceph osd pool set {poolname} size {num}

8、设置degrade最小副本数

ceph osd pool set {poolname} min_size {num}

=============================================================================================================================================
=============================================================================================================================================

###4)创建文件系统

####先查看管理节点状态,默认是没有管理节点的。
[ceph@ceph-001 ~]$ ceph mds stat
e1:
  
####创建管理节点(ceph-admin作为管理节点)。
需要注意:如果不创建mds管理节点,client客户端将不能正常挂载到ceph集群!!
[ceph@ceph-001 ~]$ pwd
/home/ceph
[ceph@ceph-001 ~]$ cd cluster/
[ceph@ceph-001 cluster]$ ceph-deploy mds create ceph-001 ceph-002 ceph-003
  
####再次查看管理节点状态,发现已经在启动中
    [ceph@ceph-001 cluster]$ ceph mds stat
    e2:, 1 up:standby
     
    [ceph@ceph-001 cluster]$ sudo systemctl status ceph-mds@ceph-001
    [ceph@ceph-001 cluster]$ ps -ef|grep cluster|grep ceph-mds
    ceph     29093     1  0 12:46 ?        00:00:00 /usr/bin/ceph-mds -f --cluster ceph --id ceph-001 --setuser ceph --setgroup ceph
  
####创建pool,pool是ceph存储数据时的逻辑分区,它起到namespace的作用
[ceph@ceph-001 cluster]$ ceph osd lspools                             #先查看pool
0 rbd,
  
####新创建的ceph集群只有rdb一个pool。这时需要创建一个新的存储池pool

示例:
[ceph@ceph-001 cluster]$ sudo ceph osd pool create cephfs_data 64         #后面的数字是PG的数量
pool 'cephfs_data' created
  
[ceph@ceph-001 cluster]$ sudo ceph osd pool create cephfs_metadata 64     #创建pool的元数据
pool 'cephfs_metadata' created
报错处理:
[ceph@ceph-001 cluster]$ sudo ceph osd pool create cephfs_metadata 128
Error ERANGE:  pg_num 128 size 3 would mean 768 total pgs, which exceeds max 750 (mon_max_pg_per_osd 250 * num_in_osds 3)
[ceph@ceph-001 cluster]$ 
[ceph@ceph-001 cluster]$ sudo ceph osd pool create cephfs_metadata 64
pool 'cephfs_metadata' created

####用fs new 命令创建文件系统了: 
    [ceph@ceph-001 cluster]$ sudo ceph fs new mycephfs cephfs_metadata cephfs_data
    new fs with metadata pool 2 and data pool 1

####查看fs状态
[ceph@ceph-001 cluster]$ sudo ceph fs ls
name: cephfs, metadata pool: cephfs_metadata, data pools: [cephfs_data ]
####查看pool状态
    [ceph@ceph-001 cluster]$ sudo ceph osd lspools
    0 rbd,1 cephfs_data,2 cephfs_metadata,
  
####检查mds管理节点状态(MDS服务器达到active状态)
    [ceph@ceph-001 cluster]$ sudo ceph mds stat
    e5: 1/1/1 up {0=ceph-001=up:active}
  
####查看ceph集群状态
    [ceph@ceph-001 cluster]$ sudo ceph -s
    cluster 33bfa421-8a3b-40fa-9f14-791efca9eb96
    health HEALTH_OK
     monmap e1: 1 mons at {ceph-001=172.16.1.205:6789/0}
             election epoch 3, quorum 0 ceph-001
      fsmap e5: 1/1/1 up {0=ceph-001=up:active}           多了此行状态
      osdmap e19: 3 osds: 3 up, 3 in
            flags sortbitwise,require_jewel_osds
      pgmap v48: 84 pgs, 3 pools, 2068 bytes data, 20 objects
        101 MB used, 45945 MB / 46046 MB avail
          84 active+clean
  
####查看ceph集群端口
    [ceph@ceph-001 cluster]$ sudo lsof -i:6789
    COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
    ceph-mon 28190 ceph   10u  IPv4  70217      0t0  TCP ceph-001:smc-https (LISTEN)
    ceph-mon 28190 ceph   19u  IPv4  70537      0t0  TCP ceph-001:smc-https->ceph-node1:41308 (ESTABLISHED)
    ceph-mon 28190 ceph   20u  IPv4  70560      0t0  TCP ceph-001:smc-https->ceph-node2:48516 (ESTABLISHED)
    ceph-mon 28190 ceph   21u  IPv4  70583      0t0  TCP ceph-001:smc-https->ceph-node3:44948 (ESTABLISHED)
    ceph-mon 28190 ceph   22u  IPv4  72643      0t0  TCP ceph-001:smc-https->ceph-001:51474 (ESTABLISHED)
    ceph-mds 29093 ceph    8u  IPv4  72642      0t0  TCP ceph-001:51474->ceph-001:smc-https (ESTABLISHED)

###5)client端挂载ceph存储(采用fuse方式)

####安装ceph-fuse(这里的客户机是ceph-client系统)
    [root@ceph-client ~]yum install -y ceph-fuse ceph
 
####创建挂载目录
[root@ceph-client ~]mkdir /cephfs
 
####复制配置文件
    将ceph配置文件ceph.conf从管理节点copy到client节点(172.16.1.205为管理节点)
    [root@ceph-client /]# yum install rsync -y 安装rsync
    [root@ceph-001 /]# yum install rsync -y  安装rsync
    [root@ceph-client ~]rsync -e "ssh -p22" -avpgolr [email protected]:/etc/ceph/ceph.conf /etc/ceph/
    或者
    [root@ceph-client ~]rsync -e "ssh -p22" -avpgolr [email protected]:/home/ceph/cluster/ceph.conf /etc/ceph/    两个路径下的文件内容一样
     或者
    [ceph@ceph-001 ceph]$ scp -r ceph.conf [email protected]:/etc/ceph/
    
    复制密钥
    将ceph的ceph.client.admin.keyring从管理节点copy到client节点
    [root@ceph-client ~]rsync -e "ssh -p22" -avpgolr [email protected]:/etc/ceph/ceph.client.admin.keyring /etc/ceph/
    或者
    [root@ceph-client ~]rsync -e "ssh -p22" -avpgolr [email protected]:/home/ceph/cluster/ceph.client.admin.keyring /etc/ceph/
    或者
    [ceph@ceph-001 ceph]$ scp -r ceph.client.admin.keyring [email protected]:/etc/ceph/
    
####查看ceph授权
    [root@ceph-client ~]ceph auth list
        installed auth entries:
         
        mds.ceph-001
            key: AQAZZxdbH6uAOBAABttpSmPt6BXNtTJwZDpSJg==
            caps: [mds] allow
            caps: [mon] allow profile mds
            caps: [osd] allow rwx
        osd.0
            key: AQCuWBdbV3TlBBAA4xsAE4QsFQ6vAp+7pIFEHA==
            caps: [mon] allow profile osd
            caps: [osd] allow *
        osd.1
            key: AQC6WBdbakBaMxAAsUllVWdttlLzEI5VNd/41w==
            caps: [mon] allow profile osd
            caps: [osd] allow *
        osd.2
            key: AQDJWBdbz6zNNhAATwzL2FqPKNY1IvQDmzyOSg==
            caps: [mon] allow profile osd
            caps: [osd] allow *
        client.admin
            key: AQCNWBdbf1QxAhAAkryP+OFy6wGnKR8lfYDkUA==
            caps: [mds] allow *
            caps: [mon] allow *
            caps: [osd] allow *
        client.bootstrap-mds
            key: AQCNWBdbnjLILhAAT1hKtLEzkCrhDuTLjdCJig==
            caps: [mon] allow profile bootstrap-mds
        client.bootstrap-mgr
            key: AQCOWBdbmxEANBAAiTMJeyEuSverXAyOrwodMQ==
            caps: [mon] allow profile bootstrap-mgr
        client.bootstrap-osd
            key: AQCNWBdbiO1bERAARLZaYdY58KLMi4oyKmug4Q==
            caps: [mon] allow profile bootstrap-osd
        client.bootstrap-rgw
            key: AQCNWBdboBLXIBAAVTsD2TPJhVSRY2E9G7eLzQ==
            caps: [mon] allow profile bootstrap-rgw
 
 
####将ceph集群存储挂载到客户机的/cephfs目录下
    [root@ceph-client ~]ceph-fuse -m 172.16.1.205:6789 /cephfs
    2018-06-06 14:28:54.149796 7f8d5c256760 -1 init, newargv = 0x4273580 newargc=11
    ceph-fuse[16107]: starting ceph client
    ceph-fuse[16107]: starting fuse
     
    [root@ceph-client ~]df -h
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/mapper/vg_ceph-client02-lv_root
                           50G  3.5G   44G   8% /
    tmpfs                 1.9G     0  1.9G   0% /dev/shm
    /dev/vda1             477M   41M  412M   9% /boot
    /dev/mapper/vg_ceph-client02-lv_home
                           45G   52M   43G   1% /home
    /dev/sdb1              20G  5.1G   15G  26% /data/osd1
    ceph-fuse              45G  100M   45G   1% /cephfs
     
    由上面可知,已经成功挂载了ceph存储,三个osd节点,每个节点有100G(在节点上通过"lsblk"命令可以查看ceph data分区大小),一共300G!
    
    sudo systemctl start ceph-fuse@/mnt.service

    sudo systemctl enable ceph-fuse@/mnt.service
 
####用内核驱动挂载 CEPH 文件系统
要挂载 Ceph 文件系统,如果你知道监视器 IP 地址可以用 mount 命令、或者用 mount.ceph 工具来自动解析监视器 IP 地址。例如:

sudo mkdir /mnt/mycephfs
sudo mount -t ceph 172.16.1.205:6789:/ /mnt/mycephfs
要挂载启用了 cephx 认证的 Ceph 文件系统,你必须指定用户名、密钥。

sudo mount -t ceph 172.16.1.205:6789:/ /mnt/mycephfs -o name=admin,secret=AQATSKdNGBnwLhAAnNDKnH65FmVKpXZJVasUeQ==
前述用法会把密码遗留在 Bash 历史里,更安全的方法是从文件读密码。例如:

sudo mount -t ceph 172.16.1.205:6789:/ /mnt/mycephfs -o name=admin,secretfile=/etc/ceph/admin.secret 
 
####取消ceph存储的挂载
[root@ceph-client ~]umount /cephfs
 
    温馨提示:
    当有一半以上的OSD节点挂掉后,远程客户端挂载的Ceph存储就会使用异常了,即暂停使用。比如本案例中有3个OSD节点,当其中一个OSD节点挂掉后(比如宕机),
    客户端挂载的Ceph存储使用正常;但当有2个OSD节点挂掉后,客户端挂载的Ceph存储就不能正常使用了(表现为Ceph存储目录下的数据读写操作一直卡着状态),
    当OSD节点恢复后,Ceph存储也会恢复正常使用。OSD节点宕机重新启动后,osd程序会自动起来(通过监控节点自动起来)
    
================================================================================================================================================
================================================================================================================================================

###6)块存储及块设备命令

    rbd 命令可用于创建、罗列、内省和删除块设备映像,也可克隆映像、创建快照、回滚快照、查看快照等等。 rbd 命令用法详情见 RBD – 管理 RADOS 块设备映像。
    1. 创建pool
    $ sudo ceph osd pool create k8s-pool 32
    
    ceph osd pool application enable k8s-pool rbd
    2. 查看存储池列表
    $ sudo ceph osd lspools
    
    
    3.创建块设备镜像
    要想把块设备加入某节点,你得先在 Ceph 存储集群中创建一个映像,使用下列命令:
    
    rbd create --size {megabytes} {pool-name}/{image-name}
    rbd create foo --size 4096 --image-feature layering [-m {mon-IP}] [-k /path/to/ceph.client.admin.keyring] [-p {pool-name}]
    例如,要在 k8s这个存储池中创建一个名为 k8s-images 、大小为 10GB 的映像,执行:
    
    sudo rbd create --size 10240 k8s-pool/k8s-images
    
    sudo rbd create --size 10240 k8s-images -p k8s-pool
    
    如果创建映像时不指定存储池,它将使用默认的 rbd 存储池。例如,下面的命令将默认在 rbd 存储池中创建一个大小为 1GB 、名为 k8s-images 的映像:
    
    rbd create --size 10240 k8s-images
    
    Note 指定此存储池前必须先创建它,详情见存储池。
    4. 查看块设备镜像
    rbd info {pool-name}/{image-name}
    
    5.将块设备映射到系统内核
     rbd map {image-name}

     sudo rbd map k8s-pool/k8s-images
     
    取消映射:
    rbd unmap k8s-pool/k8s-images
      
    6. 格式化块设备镜像
      sudo mkfs.ext4 /dev/rbd/k8s-pool/k8s-images
      
    7. 挂载文件系统
     sudo mkdir /mnt/ceph-block-device
     sudo chmod 777 /mnt/ceph-block-device
     sudo mount /dev/rbd/k8s-pool/k8s-images /mnt/ceph-block-device
     cd /mnt/ceph-block-device
    8.卸载文件系统
      sudo ceph unmap /dev/rbd0
    
    罗列块设备映像
    要列出 rbd 存储池中的块设备,可以用下列命令(即 rbd 是默认存储池名字):
    
    rbd ls
    用下列命令罗列某个特定存储池中的块设备,用存储池的名字替换 {poolname} :
    
    rbd ls {poolname}
    例如:
    rbd ls k8s-pool
    
    检索映像信息
    用下列命令检索某个特定映像的信息,用映像名字替换 {image-name} :
    
    rbd info {image-name}
    例如:
    
    rbd info k8s-images
    用下列命令检索某存储池内的映像的信息,用映像名字替换 {image-name} 、用存储池名字替换 {pool-name} :
    
    rbd info {pool-name}/{image-name}
    例如:
    
    rbd info k8s-pool/k8s-images
    调整块设备映像大小
    Ceph 块设备映像是精简配置,只有在你开始写入数据时它们才会占用物理空间。然而,它们都有最大容量,就是你设置的 --size 选项。
    如果你想增加(或减小) Ceph 块设备映像的最大尺寸,执行下列命令:
    
    rbd resize --size 2048 k8s-images                 #增加设备映像(to increase)
    rbd resize --size 2048 k8s-images --allow-shrink  #减小设备映像(to decrease)
    
    删除块设备映像
    可用下列命令删除块设备,用映像名字替换 {image-name} :
    rbd rm {image-name}
    
    例如:
    rbd rm k8s-images
    
    用下列命令从某存储池中删除一个块设备,用要删除的映像名字替换 {image-name} 、用存储池名字替换 {pool-name} :
    rbd rm {pool-name}/{image-name}
    例如:
    rbd rm k8s-pool/k8s-images

===============================其他记录==========================================
----
###清除ceph存储
####清除安装包
    [ceph@ceph-001 ~]$ ceph-deploy purge ceph-001 ceph-002 ceph-003
      
    清除配置信息
    [ceph@ceph-001 ~]$ ceph-deploy purgedata ceph-001 ceph-002 ceph-003
    [ceph@ceph-001 ~]$ ceph-deploy forgetkeys
      
    每个节点删除残留的配置文件
    [ceph@ceph-001 ~]$ sudo rm -rf /var/lib/ceph/osd/*
    [ceph@ceph-001 ~]$ sudo rm -rf /var/lib/ceph/mon/*
    [ceph@ceph-001 ~]$ sudo rm -rf /var/lib/ceph/mds/*
    [ceph@ceph-001 ~]$ sudo rm -rf /var/lib/ceph/bootstrap-mds/*
    [ceph@ceph-001 ~]$ sudo rm -rf /var/lib/ceph/bootstrap-osd/*
    [ceph@ceph-001 ~]$ sudo rm -rf /var/lib/ceph/bootstrap-mon/*
    [ceph@ceph-001 ~]$ sudo rm -rf /var/lib/ceph/tmp/*
    [ceph@ceph-001 ~]$ sudo rm -rf /etc/ceph/*
    [ceph@ceph-001 ~]$ sudo rm -rf /var/run/ceph/*
     
    -----------------------------------------------------------------------
    查看ceph命令,关于ceph osd、ceph mds、ceph mon、ceph pg的命令
    [ceph@ceph-001 ~]$ ceph --help             
 
-----------------------------------------------------------------------
####如下报错:
    [ceph@ceph-001 ~]$ ceph osd tree
    2018-06-06 14:56:27.843841 7f8a0b6dd700 -1 auth: unable to find a keyring on /etc/ceph/ceph.client.admin.keyring,/etc/ceph/ceph.keyring,/etc/ceph/keyring,/etc/ceph/keyring.bin: (2) No such file or directory
    2018-06-06 14:56:27.843853 7f8a0b6dd700 -1 monclient(hunting): ERROR: missing keyring, cannot use cephx for authentication
    2018-06-06 14:56:27.843854 7f8a0b6dd700  0 librados: client.admin initialization error (2) No such file or directory
    Error connecting to cluster: ObjectNotFound
    [ceph@ceph-001 ~]$ ceph osd stat
    2018-06-06 14:55:58.165882 7f377a1c9700 -1 auth: unable to find a keyring on /etc/ceph/ceph.client.admin.keyring,/etc/ceph/ceph.keyring,/etc/ceph/keyring,/etc/ceph/keyring.bin: (2) No such file or directory
    2018-06-06 14:55:58.165894 7f377a1c9700 -1 monclient(hunting): ERROR: missing keyring, cannot use cephx for authentication
    2018-06-06 14:55:58.165896 7f377a1c9700  0 librados: client.admin initialization error (2) No such file or directory
     
####解决办法:
    [ceph@ceph-001 ~]$ sudo chmod 644 /etc/ceph/ceph.client.admin.keyring
     
    [ceph@ceph-001 ~]$ ceph osd stat
         osdmap e35: 3 osds: 3 up, 3 in
                flags sortbitwise,require_jewel_osds
    [ceph@ceph-001 ~]$ ceph osd tree
    ID WEIGHT  TYPE NAME           UP/DOWN REWEIGHT PRIMARY-AFFINITY
    -1 0.04376 root default                                         
    -2 0.01459     host ceph-node1                                  
     0 0.01459         osd.0            up  1.00000          1.00000
    -3 0.01459     host ceph-node2                                  
     1 0.01459         osd.1            up  1.00000          1.00000
    -4 0.01459     host ceph-node3                                  
     2 0.01459         osd.2            up  1.00000          1.00000
 
###常用操作
####ceph reset
ceph-deploy purge 节点1 节点2 ....
ceph-deploy purgedata 节点1 节点2 ....
ceph-deploy forgetkeys
####常用命令
rados lspools 查看池子

ceph -s 或 ceph status 查看集群状态

ceph -w 观察集群健康状态

ceph quorum_status --format json-pretty 检查ceph monitor仲裁状态

ceph df 检查集群使用情况

ceph mon stat 检查monitor状态

ceph osd stat 检查osd状态

ceph pg stat 检查pg配置组状态

ceph pg dump 列出PG

ceph osd lspools 列出存储池

ceph osd tree 检查osd的crush map

ceph auth list 列出集群的认证密钥

ceph 获取每个osd上pg的数量


###Ceph -s集群报错too many PGs per OSD

集群状态报错,如下:
# ceph -s
    cluster 1d64ac80-21be-430e-98a8-b4d8aeb18560
     health HEALTH_WARN     <-- 报错的地方
            too many PGs per OSD (912 > max 300)
     monmap e1: 1 mons at {node1=109.105.115.67:6789/0}
            election epoch 4, quorum 0 node1
     osdmap e49: 2 osds: 2 up, 2 in
            flags sortbitwise,require_jewel_osds
      pgmap v1256: 912 pgs, 23 pools, 4503 bytes data, 175 objects
            13636 MB used, 497 GB / 537 GB avail
                 912 active+clean
分析
问题原因是集群osd 数量较少,在我的测试过程中,由于搭建rgw网关、和OpenStack集成等,创建了大量的pool,每个pool要占用一些pg ,ceph集群默认每块磁盘都有默认值,
好像每个osd 为300个pgs,不过这个默认值是可以调整的,但调整得过大或者过小都会对集群的性能产生一定影响。因为我们这个是测试环境,只要能消除掉报错即可。
查询当前每个osd下最大的pg报警值:

$ ceph --show-config  | grep mon_pg_warn_max_per_osd

mon_pg_warn_max_per_osd = 300
解决方案
在配置文件中,调大集群的此选项的告警阀值;方法如下,在mon节点的ceph.conf(/etc/ceph/ceph.conf)配置文件中添加:

$ vi /etc/ceph/ceph.conf
[global]
.......
mon_pg_warn_max_per_osd = 1000
重启monitor服务:

$ systemctl restart ceph-mon.target
再次查看ceph集群状态。

$ ceph -s

cluster 1d64ac80-21be-430e-98a8-b4d8aeb18560
 health HEALTH_OK
 monmap e1: 1 mons at {node1=109.105.115.67:6789/0}
        election epoch 6, quorum 0 node1
 osdmap e49: 2 osds: 2 up, 2 in
        flags sortbitwise,require_jewel_osds
  pgmap v1273: 912 pgs, 23 pools, 4503 bytes data, 175 objects
        13636 MB used, 497 GB / 537 GB avail
             912 active+clean

====================================================================================================================
====================================================================================================================
####安装CEPH对象网关
网关服务器:ceph-001 172.16.1.205

1. 创建ceph mds
####在你的管理节点的工作目录下,给 Ceph 对象网关节点安装Ceph对象所需的软件包。例如:

[ceph@ceph-001 cluster]$ceph-deploy install --rgw ceph-001

####ceph-common 包是它的一个依赖性,所以 ceph-deploy 也将安装这个包。 ceph 的命令行工具就会为管理员准备好。
为了让你的 Ceph 对象网关节点成为管理节点,可以在管理节点的工作目录下执行以下命令:
[ceph@ceph-001 cluster]$ceph-deploy admin <node-name>

2. 创建对象网关实例
Ceph 对象存储使用 Ceph 对象网关守护进程( radosgw ,RGW),内嵌了Civetweb服务器与FastCGI 模块。
其中Civetweb服务器默认使用tcp 7480端口。
1)变更默认端口(option)
# 变更Civetweb服务器默认端口,可修改ceph.conf文件,增加[client.rgw.<GATEWAY-NODE>]字段,其中“GATEWAY-NODE”为所在网关节点的短主机名,即:hostname -s;
# 可在部署服务器修改后分发到各网关节点,也可在各网关节点独立修改;
# [client.rgw.<GATEWAY-NODE>]字段与[global]字段在相同层级,且1个网关节点使用1个字段,其中”client”表示客户端配置,“rgw”表示客户端类型,“GATEWAY-NODE”标识实例名;
[ceph@ceph-001 cephcluster]$ cat ceph.conf 
[client.rgw.ceph=001]
rgw_frontends = "civetweb port=80"
[client.rgw.ceph-002]
rgw_frontends = "civetweb port=80"
[client.rgw.ceph-003]
rgw_frontends = "civetweb port=80" 

# 从部署服务器分发ceph.conf
[cephde@ceph01 cephcluster]$ ceph-deploy --overwrite-conf config push ceph-001 ceph-002 ceph-003

2)创建实例
####新建网关实例
# 创建后,在各网关节点对应的守护进程启动;
# 如果ceph.conf配置文件变更,可在对应节点重启服务
在你的管理节点的工作目录下,使用命令在 Ceph 对象网关节点上新建一个 Ceph对象网关实例。举例如下:

[ceph@ceph-001 cluster]$ceph-deploy rgw create ceph-001

# 查看服务
[ceph@ceph-001 ~]# systemctl status [email protected]

# 重启服务
[ceph@ceph-001 ~]# systemctl restart [email protected]

# 查看端口
[ceph@ceph01 ~]# netstat -tunlp | grep radosgw

# 创建实例后,同时创建部分默认pool;
# 或:”rados df” 与 “ceph osd pool ls”
[ceph@ceph-001 ~]# ceph osd lspools

3)访问
# 格式:http://RGW-IP:port 
[ceph@ceph-001 ~]# curl http://172.16.1.205
# 如果网关实例正常运行,响应如下:
<?xml version="1.0" encoding="UTF-8"?>
<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <Owner>
        <ID>anonymous</ID>
        <DisplayName></DisplayName>
    </Owner>
    <Buckets>
    </Buckets>
</ListAllMyBucketsResult>

三.验证
使用REST接口验证,步骤如下:

首先创建适用于s3接口的ceph对象网关用户;
基于已创建的用户,创建适用于swift接口的子用户;
验证用户是否能访问网关。
1. 创建用户
1)创建用于S3访问的RADOSGW用户
# “--uid”与“--display-name”自定义;
# 返回结果中,keys->access_key 与 keys->secret_key 是访问验证时需要的值

$ radosgw-admin user create --uid="gwuser" --display-name="Gw User"

[ceph@ceph-001 cluster]$ radosgw-admin user create --uid="gwuser" --display-name="Gw User" --system
{
    "user_id": "gwuser",
    "display_name": "Gw User",
    "email": "",
    "suspended": 0,
    "max_buckets": 1000,
    "auid": 0,
    "subusers": [],
    "keys": [
        {
            "user": "gwuser",
            "access_key": "Q8C9P5WL117MEASJK03M",
            "secret_key": "ghb6jflmbkR9j6zInaX3O9Tz0mFOZuXaWvBoGX5E"
        }
    ],
    "swift_keys": [],
    "caps": [],
    "op_mask": "read, write, delete",
    "default_placement": "",
    "placement_tags": [],
    "bucket_quota": {
        "enabled": false,
        "check_on_raw": false,
        "max_size": -1,
        "max_size_kb": 0,
        "max_objects": -1
    },
    "user_quota": {
        "enabled": false,
        "check_on_raw": false,
        "max_size": -1,
        "max_size_kb": 0,
        "max_objects": -1
    },
    "temp_url_keys": [],
    "type": "rgw",
    "mfa_ids": []
}

[ceph@ceph-001 cluster]$ radosgw-admin user info --uid=gwuser


2)创建SWITF用户
Swift用户创建分两步:

创建子用户;
生成秘钥。
# 创建子用户,基于已创建的s3用户;
# 赋予全权限
[ceph@ceph-001 cluster]$ radosgw-admin subuser create --uid=gwuser --subuser=gwuser:swift --access=full
{
    "user_id": "gwuser",
    "display_name": "Gw User",
    "email": "",
    "suspended": 0,
    "max_buckets": 1000,
    "auid": 0,
    "subusers": [
        {
            "id": "gwuser:swift",
            "permissions": "full-control"
        }
    ],
    "keys": [
        {
            "user": "gwuser",
            "access_key": "Q8C9P5WL117MEASJK03M",
            "secret_key": "ghb6jflmbkR9j6zInaX3O9Tz0mFOZuXaWvBoGX5E"
        }
    ],
    "swift_keys": [
        {
            "user": "gwuser:swift",
            "secret_key": "VxgDAOcgUvhxDf2pQ4F3cDlVnFAEOjVJlQZxVo6Y"
        }
    ],
    "caps": [],
    "op_mask": "read, write, delete",
    "default_placement": "",
    "placement_tags": [],
    "bucket_quota": {
        "enabled": false,
        "check_on_raw": false,
        "max_size": -1,
        "max_size_kb": 0,
        "max_objects": -1
    },
    "user_quota": {
        "enabled": false,
        "check_on_raw": false,
        "max_size": -1,
        "max_size_kb": 0,
        "max_objects": -1
    },
    "temp_url_keys": [],
    "type": "rgw",
    "mfa_ids": []
}

# 生成秘钥;
# 返回结果中,swift_keys ->secret_key 是访问验证时需要的值
[ceph@ceph-001 cluster]$ radosgw-admin key create --subuser=gwuser:swift --key-type=swift --gen-secret
{
    "user_id": "gwuser",
    "display_name": "Gw User",
    "email": "",
    "suspended": 0,
    "max_buckets": 1000,
    "auid": 0,
    "subusers": [
        {
            "id": "gwuser:swift",
            "permissions": "full-control"
        }
    ],
    "keys": [
        {
            "user": "gwuser",
            "access_key": "Q8C9P5WL117MEASJK03M",
            "secret_key": "ghb6jflmbkR9j6zInaX3O9Tz0mFOZuXaWvBoGX5E"
        }
    ],
    "swift_keys": [
        {
            "user": "gwuser:swift",
            "secret_key": "pPJGvSxfWvfjXLghNbBsNMb1pVPsFEDpe1wTgXTH"
        }
    ],
    "caps": [],
    "op_mask": "read, write, delete",
    "default_placement": "",
    "placement_tags": [],
    "bucket_quota": {
        "enabled": false,
        "check_on_raw": false,
        "max_size": -1,
        "max_size_kb": 0,
        "max_objects": -1
    },
    "user_quota": {
        "enabled": false,
        "check_on_raw": false,
        "max_size": -1,
        "max_size_kb": 0,
        "max_objects": -1
    },
    "temp_url_keys": [],
    "type": "rgw",
    "mfa_ids": []
}

2. 访问验证
1)测试S3访问
测试采用python脚本完成,脚本流程如下:测试脚本连接radosgw,创建bucket,list bucket。

# 客户端需要安装python-boto
[root@ceph-client ~]# yum install -y python-boto

# 编辑测试脚本;
# 注意”access_key”,”secret_key”,”host”与”port”值修改
[root@ceph-client ~]# vim s3.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#新建一个连接
import boto
import boto.s3.connection

access_key = 'Q8C9P5WL117MEASJK03M'
secret_key = 'ghb6jflmbkR9j6zInaX3O9Tz0mFOZuXaWvBoGX5E'

conn = boto.connect_s3(
        aws_access_key_id=access_key,
        aws_secret_access_key=secret_key,
        host='172.16.1.205', port=80,
        is_secure=False, calling_format=boto.s3.connection.OrdinaryCallingFormat(),
       )
#新建一个 BUCKET
bucket = conn.create_bucket('myfs-bucket')

#列出用户的所有 BUCKET
for bucket in conn.get_all_buckets():
    print "{name}\t{created}".format(
        name=bucket.name,
        created=bucket.creation_date,
)

#列出 BUCKET 的内容
for key in bucket.list():
        print "{name}\t{size}\t{modified}".format(
                name = key.name,
                size = key.size,
                modified = key.last_modified,
                )
                
#删除 BUCKET
//conn.delete_bucket(bucket.name)

#新建一个对象(下面的代码会新建一个内容是字符串``”Hello World!”`` 的文件 hello.txt。)

key = bucket.new_key('hello.txt')
key.set_contents_from_string('Hello World!')

#修改一个对象的 ACL(下面的代码会将对象 hello.txt 的权限变为公开可读,而将 secret_plans.txt 的权限设为私有。)

hello_key = bucket.get_key('hello.txt')
hello_key.set_canned_acl('public-read')
plans_key = bucket.get_key('secret_plans.txt')
plans_key.set_canned_acl('private')
#下载一个对象 (到文件)下面的代码会下载对象 perl_poetry.pdf 并将它存到位置 C:\Users\larry\Documents

key = bucket.get_key('perl_poetry.pdf')
key.get_contents_to_filename('/home/larry/documents/perl_poetry.pdf')

#删除一个对象
下面的代码会删除对象 goodbye.txt

bucket.delete_key('goodbye.txt')

#生成对象的下载 URLS (带签名和不带签名)
//下面的代码会为 hello.txt 生成一个无签名为下载URL。 这个操作是生效是因为前面我们已经设置 hello.txt 的 ACL 为公开可读。
//下面的代码同时会为 secret_plans.txt 生成一个有效时间是一个小时的带签名的下载 URL。带签名的下载 URL 在这个时间内是可用的,
//即使对象的权限是私有(当时间到期后 URL 将不可用)。

hello_key = bucket.get_key('hello.txt')
hello_url = hello_key.generate_url(0, query_auth=False, force_http=True)
print hello_url

plans_key = bucket.get_key('secret_plans.txt')
plans_url = plans_key.generate_url(3600, query_auth=True, force_http=True)
print plans_url

#输出形式类似下面这样:

http://objects.dreamhost.com/my-bucket-name/hello.txt
http://objects.dreamhost.com/my-bucket-name/secret_plans.txt?Signature=XXXXXXXXXXXXXXXXXXXXXXXXXXX&Expires=1316027075&AWSAccessKeyId=XXXXXXXXXXXXXXXXXXX

# 运行脚本,返回结果符合预期
[root@ceph-client ~]# python s3.py
 

2)测试Swift访问
测试采用swift客户端进行。

# 安装swift客户端
[root@ceph-client ~]# yum install python-setuptools
[root@ceph-client ~]# easy_install pip
[root@ceph-client ~]# pip install --upgrade setuptools
[root@ceph-client ~]# pip install --upgrade python-swiftclient

# 命令格式:swift -A http://{IP ADDRESS}:{port}/auth/1.0 -U USER:swift -K '{swift_secret_key}' list;
# 这里基于s3测试生成的bucket,list bucker,返回结果符合预期
[root@ceph-client ~]# swift -A http://172.16.1.205/auth/1.0 -U gwuser:swift -K 'pPJGvSxfWvfjXLghNbBsNMb1pVPsFEDpe1wTgXTH' list


###PYTHON SWIFT 实例

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#新建连接

import swiftclient
user = 'account_name:username'
key = 'your_api_key'

conn = swiftclient.Connection(
        user=user,
        key=key,
        authurl='https://objects.dreamhost.com/auth',
)
#创建容器 (下面创建一个名为 my-new-container 的新容器:)

container_name = 'my-new-container'
conn.put_container(container_name)

#创建对象 (下面从名为 my_hello.txt 的本地文件创建一个名为 hello.txt 的文件:)

with open('my_hello.txt', 'r') as hello_file:
        conn.put_object(container_name, 'hello.txt',
                        contents=hello_file.read(),
                        content_type='text/plain')
                        
#罗列自己拥有的容器(下面获取你拥有的容器列表,并打印容器名:)

for container in conn.get_account()[1]:
        print container['name']
//其输出大致如此:
mahbuckat1
mahbuckat2
mahbuckat3

#罗列一容器的内容(获取容器中对象的列表,并打印各对象的名字、文件尺寸、和最后修改时间:)

for data in conn.get_container(container_name)[1]:
        print '{0}\t{1}\t{2}'.format(data['name'], data['bytes'], data['last_modified'])
        
//其输出大致如此:

myphoto1.jpg 251262  2011-08-08T21:35:48.000Z
myphoto2.jpg 262518  2011-08-08T21:38:01.000Z

#检索一个对象 (下载对象 hello.txt 并保存为 ./my_hello.txt :)

obj_tuple = conn.get_object(container_name, 'hello.txt')
with open('my_hello.txt', 'w') as my_hello:
        my_hello.write(obj_tuple[1])
        
#删除对象 (删除对象 goodbye.txt :)

conn.delete_object(container_name, 'hello.txt')

#删除一个容器 (Note 容器必须是空的!否则请求不会成功!)

conn.delete_container(container_name)

[ceph@ceph-001 cluster]$ ceph dashboard set-rgw-api-access-key Q8C9P5WL117MEASJK03M
Option RGW_API_ACCESS_KEY updated
[ceph@ceph-001 cluster]$ ceph dashboard set-rgw-api-access-key ghb6jflmbkR9j6zInaX3O9Tz0mFOZuXaWvBoGX5E
Option RGW_API_ACCESS_KEY updated

[ceph@ceph-001 cluster]$ ceph dashboard set-rgw-api-host 172.16.1.205
Option RGW_API_HOST updated
[ceph@ceph-001 cluster]$ ceph dashboard set-rgw-api-port 80
Option RGW_API_PORT updated

####在网关服务成功运行后,你可以使用未经授权的请求来访问端口 7480 ,就像这样:
http://ceph-001:7480

http://172.16.1.205:7480

如果网关实例工作正常,你接收到的返回信息大概如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
       <Owner>
       <ID>anonymous</ID>
       <DisplayName></DisplayName>
   </Owner>
   <Buckets>
   </Buckets>
</ListAllMyBucketsResult>

###在任何时候如果你遇到麻烦,而你也想重新来一次,执行下面的命令来清除配置:

ceph-deploy purge <gateway-node1> [<gateway-node2>]
ceph-deploy purgedata <gateway-node1> [<gateway-node2>]

注:如果你执行了 purge, 你必须重新安装 Ceph.

####修改默认端口
Civetweb 默认运行在端口 7480 之上.。如果想修改这个默认端口 (比如使用端口 80),修改你的管理节点的工作目录下的 Ceph 配置文件。
 添加一节,以 [client.rgw.<gateway-node>] 作为名字,使用你的 Ceph 对象网关节点的短主机名替换其中的 <gateway-node> (如, hostname -s).

Note 在 0.94 版本中,Ceph 对象网关不再支持 SSL。你可以设置一个支持 SSL 的反向代理服务器来将 HTTPS 请求转为HTTP请求发给 CivetWeb。
比如, 如果你的主机名是 gateway-node1, 在 [global] 节后添加的节名如下:

[client.rgw.gateway-node1]
rgw_frontends = "civetweb port=80"

Note 请确保在 rgw_frontends 的键值对中 port=<port-number> 内部没有红格。 节名 [client.rgw.gateway-node1] 表示接下来的 Ceph 配置文件配置了一个 Ceph 存储集群的客户端,
这个客户端的类型是Ceph 对象网关存储 (比如, rgw), 同时实例名是 gateway-node1.
将该配置文件推送到你的 Ceph 对象网关节点(也包括其他 Ceph 节点):

ceph-deploy --overwrite-conf config push <gateway-node> [<other-nodes>]

ceph-deploy --overwrite-conf config push ceph-001 ceph-002 ceph-003

为了使新配置的端口生效,需要重启 Ceph 对象网关:

sudo systemctl restart ceph-radosgw.service

最后,需要确保你选择的端口在节点的防火墙配置中是开放的 (比如, 端口 80)。 如果它不是开放的,将它设为开放并重启防火墙。 如果你是用的是 firewald,执行下面的命令:

sudo firewall-cmd --list-all
sudo firewall-cmd --zone=public --add-port 80/tcp --permanent
sudo firewall-cmd --reload
如果你使用 iptables, 执行:
sudo iptables --list
sudo iptables -I INPUT 1 -i <iface> -p tcp -s <ip-address>/<netmask> --dport 80 -j ACCEPT
替换其中的 <iface> and <ip-address>/<netmask> 为你的 Ceph 对象网关节点的实际值。
一旦你完成了 iptables 的配置, 请确保你已经将本次更改持久化,这样它在你的 Ceph 对象网关节点重启也依然生效。持久化请执行:
sudo apt-get install iptables-persistent
会有一个终端界面弹出。选择 yes 来保存当前 IPv4 的 iptables 规则到文件 /etc/iptables/rules.v4 中,当前的 IPv6 iptables 规则到文件 /etc/iptables/rules.v6 中。
在前面一步设置的 IPv4 iptables规则t将会被写入文件``/etc/iptables/rules.v4`` ,这样就实现了持久化,重启也依然生效。
如果你在安装``iptables-persistent`` 后有新增了新的 IPv4 iptables 规则,你需要使用 root 执行下面的命令:
iptables-save > /etc/iptables/rules.v4
从 APACHE 迁移到 CIVETWEB
如果你在0.80或以上版本的 Ceph 存储上使用 Apache 和 FastCGI 来构建 Ceph 对象网关,实际上你已经运行了 Civetweb –它随着 ceph-radosgw 进程启动而启动,
默认情况下运行在 7480 端口,因此它不会跟基于 Apache 和 FastCGI 安装的以及其他常用的web服务所使用的端口冲突。迁移到使用 Civetweb 首先需要删除您的 Apache。
然后,您必须从 Ceph 配置文件中删除 Apache 和 FastCGI 的设置并重置 rgw_frontends 到 Civetweb。

回顾使用 ceph-deploy 来安装 Ceph 对象网关的描述,注意到它的配置文件只有一个名为 rgw_frontends 的设置(这是假设你选择改变默认端口)。
ceph-deploy 会生成对象网关的数据目录和 keyring,并将keyring放在 /var/lib/ceph/radosgw/{rgw-intance} 目录下。
从这个目录上看这个守护进程是在默认位置,然而你也可以在 Ceph 配置文件中指定不同的位置。
因为你已经有密钥和数据目录,因此如果你使用的是默认路径之外的其他目录,你就需要在 Ceph 配置文件中维护这些路径。

一个典型的基于Apache部署的Ceph对象网关配置文件类似下面的样例:

在 Red Hat Enterprise Linux 系统上:

[client.radosgw.gateway-node1]
host = {hostname}
keyring = /etc/ceph/ceph.client.radosgw.keyring
rgw socket path = ""
log file = /var/log/radosgw/client.radosgw.gateway-node1.log
rgw frontends = fastcgi socket\_port=9000 socket\_host=0.0.0.0
rgw print continue = false
在 Ubuntu 系统上:

[client.radosgw.gateway-node]
host = {hostname}
keyring = /etc/ceph/ceph.client.radosgw.keyring
rgw socket path = /var/run/ceph/ceph.radosgw.gateway.fastcgi.sock
log file = /var/log/radosgw/client.radosgw.gateway-node1.log
为了能够使用 Civetweb,需要做一点修改,简单地删除 Apache 特有的设置如 rgw_socket_path 和 rgw_print_continue 。然后,
改变 rgw_frontends 的设置来指向 Civetweb 而不是 Apache FastCGI 作为前端,并指定您想要使用的端口号。例如:

[client.radosgw.gateway-node1]
host = {hostname}
keyring = /etc/ceph/ceph.client.radosgw.keyring
log file = /var/log/radosgw/client.radosgw.gateway-node1.log
rgw_frontends = civetweb port=80
最后,重启 Ceph 对象网关。在 Red Hat Enterprise Linux 请执行:

sudo systemctl restart ceph-radosgw.service
在 Ubuntu 上执行:

sudo service radosgw restart id=rgw.<short-hostname>
如果你使用的端口还没有在防护墙端放开,你还需要在你的防火墙开放该端口。

配置 BUCKET SHARDING
Ceph 对象网关在 index_pool 中存储 bucket 的索引数据,默认情况下是资源池 .rgw.buckets.index 。有时用户喜欢把很多对象(几十万到上百万的对象)存放到同一个 bucket 中。
如果你不使用网关的管理接口来为每个 bucket 的最大对象数设置配额,那么当一旦用户存放大量的对象到一个 bucket 中时,bucket 索引的性能会呈现明显的下降。

在0.94版本的 Ceph 中,您可以给 bucket 索引进行分片,这样在你允许 bucket 中有大量对象时,能够有助于防止出现性能瓶颈。
设置项的 “rgw_override_bucket_index_max_shards“ 允许您设置一个 bucket 的最大分片数。它的默认值为 0 ,这意味着 bucket 索引分片功能在默认情况下情况下是关闭的。

开启 bucket 的索引分片功能,只需给 rgw_override_bucket_index_max_shards 设置一个大于 0 的值。

简单的配置,只需要在 Ceph 配置文件中加入 rgw_override_bucket_index_max_shards 。将其添加在 [global] 部分来设置一个系统层面生效的值。你也可以在 Ceph 配置文件中将它设置为某一个实例生效。

一旦你在 Ceph 配置文件中修改了你的bucket分片设置,你需要重启网关。在 Red Hat Enterprise Linux 请执行:

sudo systemctl restart ceph-radosgw.service
在 Ubuntu 上请执行:

sudo service radosgw restart id=rgw.<short-hostname>
对于异地场景的配置而言,为了灾备每一个 zone 都有一个不同的 index_pool 设置。为了保持这个参数在一个 region 的所有 zone 中保持一致,
你可以在 region 的网关配置中指定 rgw_override_bucket_index_max_shards 。举例如下:

radosgw-admin region get > region.json
打开 region.json 的文件,为每一个 zone 编辑 bucket_index_max_shards 的设置。保存 region.json 文件并重置 region。举例如下:

radosgw-admin region set < region.json
一旦你更新了你的 region,你需要更新 region map。举例如下:

radosgw-admin regionmap update --name client.rgw.ceph-client
其中的 client.rgw.ceph-client 是网关用户的名字。

Note 通过 CRUSH 规则集将索引资源池 (如果可以为每一个zone设置) 映射到基于 SSD的 OSD 上也能够提升 bucket 索引的性能。
给 DNS 添加泛域名解析
为了通过 S3 风格的子域名来使用 Ceph(如:bucket-name.domain-name.com),你应该给你的 ceph-radosgw 守护进程所在服务器在 DNS 服务器上给它的 DNS 记录添加泛域名解析。

这个 DNS 地址也必须在 Ceph 配置文件中通过 rgw dns name = {hostname} 设置项来指定。

对于 dnsmasq 而言,通过在主机名前添加点号 (.) 来实现添加 DNS 地址设置:

address=/.{hostname-or-fqdn}/{host-ip-address}
举例如下:

address=/.gateway-node1/192.168.122.75
对于 bind 而言,给 DNS 记录添加一个泛域名解析。举例如下:

$TTL    604800
@       IN      SOA     gateway-node1. root.gateway-node1. (
                              2         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
@       IN      NS      gateway-node1.
@       IN      A       192.168.122.113
*       IN      CNAME   @
重启你的 DNS 服务,然后使用子域名 ping 你的服务器来确保你的 ceph-radosgw 进程能够出来子域名请求:

ping mybucket.{hostname}
举例如下:

ping mybucket.gateway-node1
开启 DEBUGGING (如果需要)
一旦你完成了安装过程,如果在你的配置下遇到了问题,你可以在 Ceph 配合文件的 [global] 小节下面添加调试选项,然后重启网关服务,进而帮助解决配置过程出现的问题。例如:

[global]
#append the following in the global section.
debug ms = 1
debug rgw = 20
使用网关
为了使用 REST 接口,首先需要为S3接口创建一个初始 Ceph 对象网关用户。然后,为 Swift 接口创建一个子用户。然后你需要验证创建的用户是否能够访问网关。

为 S3 访问创建 RADOSGW 用户
一个``radosgw`` 用户需要被新建并被分配权限。命令 man radosgw-admin 会提供该命令的额外信息。

为了新建用户,在 gateway host 上执行下面的命令:

sudo radosgw-admin user create --uid="testuser" --display-name="First User"
命令的输出跟下面的类似:

{
        "user_id": "testuser",
        "display_name": "First User",
        "email": "",
        "suspended": 0,
        "max_buckets": 1000,
        "auid": 0,
        "subusers": [],
        "keys": [{
                "user": "testuser",
                "access_key": "I0PJDPCIYZ665MW88W9R",
                "secret_key": "dxaXZ8U90SXydYzyS5ivamEP20hkLSUViiaR+ZDA"
        }],
        "swift_keys": [],
        "caps": [],
        "op_mask": "read, write, delete",
        "default_placement": "",
        "placement_tags": [],
        "bucket_quota": {
                "enabled": false,
                "max_size_kb": -1,
                "max_objects": -1
        },
        "user_quota": {
                "enabled": false,
                "max_size_kb": -1,
                "max_objects": -1
        },
        "temp_url_keys": []
}
Note 其中 keys->access_key 和``keys->secret_key`` 的值在访问的时候需要用来做验证
Important 请检查输出的 key。有个时候 radosgw-admin 会在生成的JSON 中的 access_key 和和 secret_key 部分包含有转义字符 \ ,
并且一些客户端不知道如何处理 JSON 中的这个字符。补救措施包括移除 JSON 中的 \ 字符,将该字符串封装到引号中,重新生成这个 key 并确保不再包含 \ ,
或者手动指定``access_key`` 和和 secret_key 。如果 radosgw-admin 生成的 JSON 中的同一个key中包含转义字符 \ 同时包含有正斜杠 / 形如 \/ ,
请只移除 JSON 转义字符 \ ,不要删除正斜杠 / ,因为在 key 中它是一个有效字符。
新建一个 SWIFT 用户
如果你想要使用这种方式访问集群,你需要新建一个 Swift 子用户。创建 Swift 用户包括两个步骤。第一步是创建用户。第二步是创建 secret key。

在``gateway host`` 上执行喜爱按的步骤:

新建 Swift 用户:

sudo radosgw-admin subuser create --uid=testuser --subuser=testuser:swift --access=full
输出类似下面这样:

{
        "user_id": "testuser",
        "display_name": "First User",
        "email": "",
        "suspended": 0,
        "max_buckets": 1000,
        "auid": 0,
        "subusers": [{
                "id": "testuser:swift",
                "permissions": "full-control"
        }],
        "keys": [{
                "user": "testuser:swift",
                "access_key": "3Y1LNW4Q6X0Y53A52DET",
                "secret_key": ""
        }, {
                "user": "testuser",
                "access_key": "I0PJDPCIYZ665MW88W9R",
                "secret_key": "dxaXZ8U90SXydYzyS5ivamEP20hkLSUViiaR+ZDA"
        }],
        "swift_keys": [],
        "caps": [],
        "op_mask": "read, write, delete",
        "default_placement": "",
        "placement_tags": [],
        "bucket_quota": {
                "enabled": false,
                "max_size_kb": -1,
                "max_objects": -1
        },
        "user_quota": {
                "enabled": false,
                "max_size_kb": -1,
                "max_objects": -1
        },
        "temp_url_keys": []
 }
新建 secret key:

sudo radosgw-admin key create --subuser=testuser:swift --key-type=swift --gen-secret
输出类似下面这样:

{
        "user_id": "testuser",
        "display_name": "First User",
        "email": "",
        "suspended": 0,
        "max_buckets": 1000,
        "auid": 0,
        "subusers": [{
                "id": "testuser:swift",
                "permissions": "full-control"
        }],
        "keys": [{
                "user": "testuser:swift",
                "access_key": "3Y1LNW4Q6X0Y53A52DET",
                "secret_key": ""
        }, {
                "user": "testuser",
                "access_key": "I0PJDPCIYZ665MW88W9R",
                "secret_key": "dxaXZ8U90SXydYzyS5ivamEP20hkLSUViiaR+ZDA"
        }],
        "swift_keys": [{
                "user": "testuser:swift",
                "secret_key": "244+fz2gSqoHwR3lYtSbIyomyPHf3i7rgSJrF\/IA"
        }],
        "caps": [],
        "op_mask": "read, write, delete",
        "default_placement": "",
        "placement_tags": [],
        "bucket_quota": {
                "enabled": false,
                "max_size_kb": -1,
                "max_objects": -1
        },
        "user_quota": {
                "enabled": false,
                "max_size_kb": -1,
                "max_objects": -1
        },
        "temp_url_keys": []
}
访问验证
测试 S3 访问
为了验证 S3 访问,你需要编写并运行一个 Python 测试脚本。S3 访问测试脚本将连接 radosgw, 新建一个新的 bucket 并列出所有的 buckets。 
aws_access_key_id 和 aws_secret_access_key 的值来自于命令``radosgw_admin`` 的返回值 access_key 和 secret_key 。

执行下面的步骤:

你需要安装 python-boto 包:

sudo yum install python-boto
新建 Python 脚本文件:

vi s3test.py
将下面的内容添加到文件中:

import boto
import boto.s3.connection

access_key = 'I0PJDPCIYZ665MW88W9R'
secret_key = 'dxaXZ8U90SXydYzyS5ivamEP20hkLSUViiaR+ZDA'
conn = boto.connect_s3(
        aws_access_key_id = access_key,
        aws_secret_access_key = secret_key,
        host = '{hostname}', port = {port},
        is_secure=False, calling_format = boto.s3.connection.OrdinaryCallingFormat(),
        )

bucket = conn.create_bucket('my-new-bucket')
    for bucket in conn.get_all_buckets():
            print "{name}".format(
                    name = bucket.name,
                    created = bucket.creation_date,
 )
将 {hostname} 替换为你配置了网关服务的节点的主机名。比如 gateway host. 将 {port} 替换为 Civetweb 所使用的端口。

运行脚本:
python s3test.py
输出类似下面的内容:
my-new-bucket 2015-02-16T17:09:10.000Z
测试 SWIFT 访问
Swift 访问的验证则可以使用``swift`` 的命令行客户端。可以通过命令 man swift 获取更多命令行选项的更多信息。

执行下面的命令安装 swift 客户端,在 Red Hat Enterprise Linux上执行:
sudo yum install python-setuptools
sudo easy_install pip
sudo pip install --upgrade setuptools
sudo pip install --upgrade python-swiftclient
在基于 Debian 的发行版上执行:

sudo apt-get install python-setuptools
sudo easy_install pip
sudo pip install --upgrade setuptools
sudo pip install --upgrade python-swiftclient
执行下面的命令验证 swift 访问:

swift -A http://{IP ADDRESS}:{port}/auth/1.0 -U testuser:swift -K '{swift_secret_key}' list
使用网关服务器的外网 IP 地址替换其中的 {IP ADDRESS} ,使用新建 swift 用户时执行的命令 radosgw-admin key create 的输出替换其中的 {swift_secret_key} 。
使用你的 Civetweb 所使用的端口替换其中 {port} ,比如默认是 7480 。如果你不替换这个端口,它的默认值是 80. 举例如下:

swift -A http://10.19.143.116:7480/auth/1.0 -U testuser:swift -K '244+fz2gSqoHwR3lYtSbIyomyPHf3i7rgSJrF/IA' list
输出类似下面这样:
my-new-bucket

==============================================================================================================================
==============================================================================================================================

ceph学习(五) s3cmd

s3cmd安装

通过pip和yum可以直接安装,没有pip的需要安装pip
yum install s3cmd

pip search s3cmd

生成秘钥
radosgw-admin user create --uid=test1 --display-name="test1" [email protected]

查看
radosgw-admin user info --uid=test1

{
    "user_id": "test1",
    "display_name": "test 1",
    "email": "[email protected]",
    "suspended": 0,
    "max_buckets": 1000,
    "auid": 0,
    "subusers": [],
    "keys": [
        {
            "user": "test1",
            "access_key": "LEEJ5TSHT0PHWGKYB3NM",
            "secret_key": "TbzEYCWsdM0j9JYXPYS6qMF3ur1hT9VBPkXongGt"
        }
    ],
    "swift_keys": [],
    "caps": [],
    "op_mask": "read, write, delete",
    "default_placement": "",
    "placement_tags": [],
    "bucket_quota": {
        "enabled": false,
        "max_size_kb": -1,
        "max_objects": -1
    },
    "user_quota": {
        "enabled": false,
        "max_size_kb": -1,
        "max_objects": -1
    },
    "temp_url_keys": []
}

s3cmd的配置

使用前需要配置Access Key ID 和 Secret Access Key
vi ~/.s3cfg

[default]
access_key = *
secret_key = *
host_base = 127.0.0.1:7480
host_bucket = 127.0.0.1:7480/%(bucket)
use_https = False


s3cmd --configure

---------------------------------------------------------------------------------------------------
s3cmd的基本使用

3.1、列举所有 Buckets。(bucket 相当于根文件夹)
s3cmd ls

3.2、创建 bucket,且 bucket 名称是唯一的,不能重复。
s3cmd mb s3://my-bucket-name

3.3、删除空 bucket
s3cmd rb s3://my-bucket-name

3.4、列举 Bucket 中的内容
s3cmd ls s3://my-bucket-name

3.5、上传 file.txt 到某个 bucket,
s3cmd put file.txt s3://my-bucket-name/file.txt

3.6、上传并将权限设置为所有人可读
s3cmd put --acl-public file.txt s3://my-bucket-name/file.txt

3.7、批量上传文件
s3cmd put ./* s3://my-bucket-name/

3.8、下载文件
s3cmd get s3://my-bucket-name/file.txt file.txt

3.9、批量下载
s3cmd get s3://my-bucket-name/* ./

3.10、删除文件
s3cmd del s3://my-bucket-name/file.txt

3.11、来获得对应的bucket所占用的空间大小
s3cmd du -H s3://my-bucket-name

3.12、设置S3 bucket的Public权限
s3cmd setacl s3://myexamplebucket.calvium.com/ --acl-public --recursive

3.13  创建用户
radosgw-admin user create --uid=test1 --display-name="test 1" [email protected]

3.14 配置文件
vi ~/.s3cfg

[default]
access_key =LEEJ5TSHT0PHWGKYB3NM 
secret_key =TbzEYCWsdM0j9JYXPYS6qMF3ur1hT9VBPkXongGt
host_base = 127.0.0.1:7480  
host_bucket =127.0.0.1:7480/%(bucket)
use_https = False


3.15 查看用户信息
radosgw-admin user info --uid=test1

=====================================================================================================

###Kubernetes配置Ceph RBD StorageClass
####1. 在Ceph上为Kubernetes创建一个存储池
# ceph osd pool create k8s 128

#####2. 创建k8s用户
# ceph auth get-or-create client.k8s mon 'allow r' osd 'allow rwx pool=k8s' -o ceph.client.k8s.keyring
 
####3. 将k8s用户的key进行base64编码(这是Kubernetes访问Ceph的密钥,会保存在Kubernetes的Secret中)
# grep key ceph.client.k8s.keyring | awk '{printf "%s", $NF}' | base64
VBGFaeN3OWJYdUZPSHhBQTNrU2E2QlUyaEF5UUV0SnNPRHdXeRT8PQ==

####4. 在Kubernetes创建访问Ceph的Secret
# echo ' apiVersion: v1
kind: Secret
metadata:
  name: ceph-k8s-secret
type: "kubernetes.io/rbd"
data:
  key: VBGFaeN3OWJYdUZPSHhBQTNrU2E2QlUyaEF5UUV0SnNPRHdXeRT8PQ==
---
apiVersion: v1
kind: Secret
metadata:
  name: ceph-001-secret
  namespace: kube-system
type: "kubernetes.io/rbd"
data:
  key: VBGFaeN3OWJYdUZPSHhBQTNrU2E2QlUyaEF5UUV0SnNPRHdXeRT8PQ== ‘ | kubectl create -f -

####5. 将访问Ceph的keyring复制到Kubernetes work节点上

  在创建Pod的时候,kubelet会调用rbd命令去检测和挂载PVC对应的rbd镜像,因此在kubelet节点上要保证存在rbd命令和访问ceph的keyring。否则创建Pod,kubelet有可能报各种各样ceph相关的错误。

  如果kubelet在worker节点上是正常运行在default namespace下的,那么安装ceph-common包,然后将keyring拷贝到/etc/ceph/目录下即可;如果kubelet是运行在容器中,那这两个操作就需要在容器中执行。

  我们的环境中,kubelet是运行在rkt容器中的,官方镜像中已经包含了ceph客户端,所以只需要将keyring拷贝到容器中。

  我们环境中使用systemctl管理kubelet,以服务的方式启动一个rkt容器来运行kubelet,修改/etc/systemd/system/kubelet.service,增加一个对应keyring的volume:

[Unit]
Description=Kubernetes Kubelet
Documentation=https://github.com/kubernetes/kubernetes
After=load-images.service
Requires=docker.service

[Service]
EnvironmentFile=/etc/cluster-envs
Environment=KUBELET_IMAGE_TAG=v1.7.10
Environment="RKT_RUN_ARGS= \
--volume ceph-keyring,kind=host,source=/etc/ceph/ceph.client.k8s.keyring \
--mount volume=ceph-keyring,target=/etc/ceph/ceph.client.k8s.keyring \
--volume modprobe,kind=host,source=/usr/sbin/modprobe \
--mount volume=modprobe,target=/usr/sbin/modprobe \
--volume lib-modules,kind=host,source=/lib/modules \
--mount volume=lib-modules,target=/lib/modules \
ExecStartPre=/usr/bin/mkdir -p /etc/ceph
ExecStart=/opt/bin/kubelet-wrapper \
--address=0.0.0.0 \
--allow-privileged=true \
--cluster-dns=192.168.192.10 \
--cluster-domain=cluster.local \
--cloud-provider='' \
--port=10250 \
--lock-file=/var/run/lock/kubelet.lock \
--exit-on-lock-contention \
--node-labels=worker=true \
--pod-manifest-path=/etc/kubernetes/manifests \
--kubeconfig=/etc/kubernetes/kubeconfig.yaml \
--require-kubeconfig=true \
--network-plugin=cni \
--cni-conf-dir=/etc/cni/net.d \
--cni-bin-dir=/opt/cni/bin \
--logtostderr=true
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
 

####6. 在Kubernetes创建ceph-rbd StorageClass

echo ‘apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
   name: ceph-rbd
provisioner: kubernetes.io/rbd
parameters:
  monitors: 10.32.24.11:6789,10.32.24.12:6789,10.32.24.13:6789
  adminId: k8s
  adminSecretName: ceph-k8s-secret
  adminSecretNamespace: kube-system
  pool: k8s
  userId: k8s
  userSecretName: ceph-k8s-secret’ | kubectl create -f -

 

####7. 将ceph-rbd设置为默认的StorageClass

 kubectl patch storageclass ceph-rbd -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
  注意集群中只能存在一个默认StorageClass,如果同时将多个StorageClass设置为默认,相当于没有设置默认StorageClass。查看StorageClass列表,默认StorageClass带有(default)标记:

# kubectl get storageclass
NAME                 TYPE
ceph-rbd (default)   kubernetes.io/rbd
ceph-sas             kubernetes.io/rbd
ceph-ssd             kubernetes.io/rbd
 

####8. 创建一个PersistentVolumeClaim

echo ‘apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nginx-test-vol1-claim
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: ceph-rbd
  resources:
    requests:
      storage: 10Gi’ | kubectl create -f -

因为指定了默认StorageClass,所以这里的storageClassName其实可以省略。

####9. 创建使用PVC的Pod

echo ‘apiVersion: v1
kind: Pod
metadata:
  name: nginx-test
spec:
  containers:
  - name: nginx
    image: nginx:latest
    volumeMounts:
      - name: nginx-test-vol1
        mountPath: /data/
        readOnly: false
  volumes:
  - name: nginx-test-vol1
    persistentVolumeClaim:
      claimName: nginx-test-vol1-claim’ | kubectl create -f -

####10. 查看容器状态
进入容器看到rbd挂载到了/data目录

kubectl exec nginx-test -it -- /bin/bash
[root@nginx-test ~]# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/rbd0        50G   52M   47G   1% /data


[ceph@ceph-001 cluster]$ cat ceph.conf
[global]
fsid = 3ec98689-56d7-49b5-b708-6967922ac338
mon_initial_members = ceph-001, ceph-002, ceph-003
mon_host = 172.16.1.205,172.16.1.206,172.16.1.207
auth_cluster_required = cephx
auth_service_required = cephx
auth_client_required = cephx
public network = 172.16.1.0/24

osd pool default size = 2
osd pool default min size = 1
osd pool default pg num = 32
osd pool default pgp num = 32

[mgr]
mgr modules = dashboard

[client.rgw.ceph-001]
rgw_frontends = "civetweb port=80"
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章