searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

Rally自动化测试及plugin开发(附源码)

2023-06-27 11:43:32
66
0

Rally概述

Rally是OpenStack社区推出的开源⾃动化测试⼯具,社区希望通过Rally来解答“How does OpenStack work at scale?”的问题。为了实现这⼀⽬的,Rally集⾃动化部署、功能验证、性能测试和分析报告于⼀体。

通过使⽤ Rally 组件,⽤户可完成 OpenStack 云计算平台的安装部署、功能验证、⼤规模负载测试(性能测试)、输出测试报告等⼀系列动作,可⽤于对 OpenStack 各个组件进⾏性能测试。作为OpenStack CI/CD 系统中的基础⼯具,帮助⽤户不断提⾼系统的 SLA(服务等级协议)、性能和稳定性。

简⽽⾔之,Rally 能够帮助⽤户完成整个 OpenStack 平台或者某个单⼀组件功能的压⼒测试,帮助⽤户验证和评估稳定系统⼯作负载的规模。其中,xrally是openstack性能测试项⽬rally的⼀个新版本,当前版本下xrally以插件化的形式⽀持openstack, docker, k8s等云环境。rally将openstack的代码从他⾃身剥离出来以rally-openstack的形式存在。

https://github.com/openstack/rally.git(rally整体框架)

https://github.com/openstack/rally-openstack.git(openstack⽀持插件)

架构分析

Rally的架构图如下,展示了Rally强⼤的功能:

Rally plugin架构图, 在rally-plugin框架下:custom task scenario, runner, SLA, deployment or context都是作为⼀个plugin存在。

其中,

scenario: ⽤代码定义运⾏的场景

runner:定义运⾏周期, 并发数,运⾏次数等

SLA:对测试结果的⼀个定义

deployment:选择测试环境

context:上下⽂,初始化环境和清理环境等操作

应用场景

对于不同的使⽤场景,Rally在测试中的流程也有所不同,主要⽀持以下三种场景:

1) 开发测试,可以评估处于开发阶段的OpenStack系统的性能,能够完成安装部署、仿真测试并输出测试结果等⼀系列动作;

2) 开发运维测试,可以基于现有的OpenStack云平台,对已经安装部署的云平台进⾏仿真测试并输出测试结果;

3) CI/CD场景测试,可以将Rally集成到CI/CD系统。

以下为三种主要场景的使⽤流程:

Rally安装

自动化脚本安装

wget -q -O https://raw.githubusercontent.com/openstack/rally/master/install_rally.sh | bash

# or using curl
curl https://raw.githubusercontent.com/openstack/rally/master/install_rally.sh | bash

DevStack allinone同步安装

git clonehttps://git.openstack.org/openstack-dev/devstack
git clonehttps://github.com/openstack/rally
cd devstack
cp samples/local.conflocal.conf

编辑local.conf⽂件,在[[local|localrc]]段⾥⾯新增如下⾏:

enable_plugin rally https://github.com/openstack/rally master

执行:

./stack.sh

容器化安装

制作rally的docker镜像,以灌注⼀些其他的python lib和⾃⼰开发的代码

# 将所有⽤到的⼯具灌注到docker中制作成镜像
FROM ubuntu:16.04
RUN sed -i s/^deb-src.*// /etc/apt/sources.list
RUN apt-get update && apt-get install --yes sudo python python-pip vim git-core && \
pip install --upgrade pip && \
useradd -u 65500 -m rally && \
usermod -aG sudo rally && \
echo "rally ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/00-rally-user
COPY ./source /home/rally/source
COPY motd /etc/motd
WORKDIR /home/rally/source
# ensure that we have all system packages installed
RUN pip install bindep && apt-get install --yes $(bindep -b | tr '\n' '
')
RUN pip install -i https://pypi.douban.com/simple . --constraint upper￾constraints.txt
--ignore-installed PyYAML && \
pip install -i https://pypi.douban.com/simple pymysql --ignore-installed
PyYAML && \
pip install -i https://pypi.douban.com/simple psycopg2 --ignore￾installed PyYAML && \
pip install os-faults && \
pip install rally-runners && \
mkdir /etc/rally && \
echo "[database]" > /etc/rally/rally.conf && \
echo "connection=sqlite:////home/rally/data/rally.db" >>
/etc/rally/rally.conf
RUN echo '[ ! -z "$TERM" -a -r /etc/motd ] && cat /etc/motd' >> /etc/bash.bashrc
# Cleanup pip
RUN rm -rf /root/.cache/
USER root
ENV HOME /home/rally
RUN mkdir -p /home/rally/data && rally db recreate
RUN apt-get -y install software-properties-common && \
apt-add-repository ppa:ansible/ansible && \
apt-get update && \
apt-get install -y ansible
# Docker volumes have specific behavior that allows this construction to
work.
# Data generated during the image creation is copied to volume only when
it's
# attached for the first time (volume initialization)
VOLUME ["/home/rally/data"]

Rally plugin开发

⾸先我们需要导⼊ class: rally.task.scenario.configure ,且在 @scenario.configure(name="my_new_plugin_name") 中定义 testcase 的名字, 这⾥定义的名字将会在 yaml ⽂件中使⽤,所以2者必须完全匹配上。

from rally.task import scenario

@scenario.configure(name="my_new_plugin_name")
class MyNewPlugin(plugin.Plugin):
    pass

context

context能够在 scenario iteration开始之前执⾏初始化操作,⽐如在执⾏⼀个场景⽤例创建虚拟机之前, 需要提前准备下载Image,那就可以把download image这个操作放在context这个plugin中。context将在scenario循环开始和结束之前和之后做为⼀个处理化和清理的任务。

from rally.task import contextfrom rally.common import loggingfrom rally
import constsfrom rally.plugins.openstack import osclients

LOG = logging.getLogger(__name__)
@context.configure(name="create_flavor", order=1000)class
CreateFlavorContext(context.Context):
    """This sample creates a flavor with specified option."""
    CONFIG_SCHEMA = {
        "type": "object",
        "$schema": consts.JSON_SCHEMA,
        "additionalProperties": False,
        "properties": {
            "flavor_name": {
                "type": "string",
           },
            "ram": {
                "type": "integer",
                "minimum": 1
           },
            "vcpus": {
                "type": "integer",
                "minimum": 1
           },
            "disk": {
                "type": "integer",
                "minimum": 1
           }
       }
   }
    def setup(self):
        """This method is called before the task starts."""
        try:
            # use rally.osclients to get necessary client instance
            nova = osclients.Clients(self.context["admin"]["credential"]).nova()
            # and than do what you need with this client
            self.context["flavor"] = nova.flavors.create(
                # context settings are stored in self.config
                name=self.config.get("flavor_name", "rally_test_flavor"),
                ram=self.config.get("ram", 1),
                vcpus=self.config.get("vcpus", 1),
                disk=self.config.get("disk", 1)).to_dict()
            LOG.debug("Flavor with id '%s'" % self.context["flavor"]["id"])
        except Exception as e:
            msg = "Can't create flavor: %s" % e.message
            if logging.is_debug():
                LOG.exception(msg)
            else:
                LOG.warning(msg)
    def cleanup(self):
        """This method is called after the task finishes."""
        try:
            nova = osclients.Clients(self.context["admin"]["credential"]).nova()
            nova.flavors.delete(self.context["flavor"]["id"])
            LOG.debug("Flavor '%s' deleted" % self.context["flavor"]["id"])
        except Exception as e:
            msg = "Can't delete flavor: %s" % e.message
            if logging.is_debug():
                LOG.exception(msg)
            else:
                LOG.warning(msg)

其中,代码的写法如下图所示

@context.configure(name="create_flavor", order=1000) # 定义context的名字
class CreateFlavorContext(context.Context) # 继承context.context的⽗类
def setup(self) # 初始化操作
def cleanup(self) # 清理操作
self.context # 所有的数据需要放置到self.context这个dict中, 作为返回值
LOG = logging.getLogger(name) # 在整个rally架构中,使⽤log打印⽇志
CONFIG_SCHEMA # init to format json data**

scenario runner

scenario runner被⽤来定义scenario以⼀种什么样⼦的格式循环运⾏,共有四类:

  • constant ,⽤于通过运⾏场景固定次数来创建恒定负载,可能是并⾏的(由 “并发”参数控制)。
  • constant_for_duration,与constant完全相同,但运⾏基准场景直到经过指定的秒数(“duration”参数)。
  • rps,它以两次连续运⾏之间的间隔执⾏基准场景,在“rps”字段中以每秒次数为单位指定。
  • serial,这对于测试新场景⾮常有⽤,因为它只是在单个线程中运⾏基准场景固定次数。

此外,可以为所有场景运⾏器(再次通过配置⽂件中的“运⾏器” 部分)提供可选的“超时”参数,该参数指定每个基准场景运⾏的超时时间(以秒为单位)。

import random
from rally.task import runnerfrom rally import consts

@runner.configure(name="random_times")
class RandomTimesScenarioRunner(runner.ScenarioRunner):
    """Sample scenario runner plugin.
   Run scenario random number of times (between min_times and max_times)
  """
    CONFIG_SCHEMA = {
        "type": "object",
        "$schema": consts.JSON_SCHEMA,
        "properties": {
            "type": {
                "type": "string"
           },
            "min_times": {
                "type": "integer",
                "minimum": 1
           },
            "max_times": {
                "type": "integer",
                "minimum": 1
           }
       },
        "additionalProperties": True
   }
    def _run_scenario(self, cls, method_name, context, args):
        # runners settings are stored in self.config
        min_times = self.config.get('min_times', 1)
        max_times = self.config.get('max_times', 1)
        for i in range(random.randrange(min_times, max_times)):
            run_args = (i, cls, method_name,
                        runner._get_scenario_context(context), args)
            result = runner._run_scenario_once(run_args)
            # use self.send_result for result of each iteration
            self._send_result(result)

Hooks

测试当我们配置变更和一些基础组件重启对整个性能和稳定性的影响。在rally架构中,hooks能够模拟绝大数故障。因为我们这里需要模拟一些系统关机, 重启等操作,所以用到了一个第三方的Lib.

os-faults被用来模拟系统故障,它通过ansible脚本来控制集群。

在使用时,调用了os-faults的human-api来kill mysql process,在这里提到的action中的内容, 都需要在os-faluts.yaml中配置,而且需要将其导入至环境变量。

hooks:
  - name: fault_injection@openstack
    args:
      action: kill mysql service on one node
    trigger:
      name: event
      args:
        unit: iteration
        at:
        - 5
export OS_FAULTS_CONFIG=os-faults.yaml
cloud_management:
  driver: universal

node_discover:
  driver: node_list
  args:
  - ip: 10.xxx.xx.14
    auth:
      username: root
      password: *********
      private_key_file: cloud_key
  - ip: 10.xxx.xx.15
    auth:
      username: root
      password: *********
      private_key_file: cloud_key
  - ip: 10.xxx.xx.16
    auth:
      username: root
      password: *********
      private_key_file: cloud_key

power_managements:
- driver: ipmi
  args:
    mac_to_bmc:
      EC:38:8F:7D:40:FF:
        address: 172.xx.xx.118
        username: root
        password: *********
      E8:4D:D0:B3:CC:3D:
        address: 172.xx.xx.119
        username: root
        password: *********
      E8:4D:D0:B3:CA:D0:
        address: 172.xx.xx.120
        username: root
        password: *********

services:
  nova-api:
    driver: system_service
    args:
      service_name: nova-api
      grep: nova-api
  glance-api:
    driver: system_service
    args:
      service_name: glance-api
      grep: glance-api
  identity:
    driver: system_service
    args:
      service_name: identity
      grep: identity
  memcached:
    driver: system_service
    args:
      service_name: memcached
      grep: memcached
  mysql:                 # name of the service
    driver: process      # name of the service driver
    args:                # arguments for the driver
      grep: mysqld
      port:
      - tcp
      - 3306
      restart_cmd: sudo systemctl restart mariadb
      start_cmd: sudo systemctl start mariadb
      terminate_cmd: sudo systemctl stop mariadb
  rabbitmq-server:
    driver: system_service
    args:
      service_name: rabbitmq-server
      grep: rabbitmq-server
    hosts:
    - 172.16.170.13

scenario

context, scenario runner等plugin都是为了scenario服务的,scenario将被重复执行来验证系统的性能和稳定性。

from rally import constsfrom rally.plugins.openstack import scenariofrom rally.task import atomicfrom rally.task import validation

@validation.add("required_services", services=[consts.Service.NOVA])@validation.add("required_platform", platform="openstack", users=True)@scenario.configure(name="ScenarioPlugin.list_flavors_useless")class ListFlavors(scenario.OpenStackScenario):
    """Sample plugin which lists flavors."""

    @atomic.action_timer("list_flavors")
    def _list_flavors(self):
        """Sample of usage clients - list flavors
        You can use self.context, self.admin_clients and self.clients which are initialized on scenario instance creation"""
        self.clients("nova").flavors.list()

    @atomic.action_timer("list_flavors_as_admin")
    def _list_flavors_as_admin(self):
        """The same with admin clients"""
        self.admin_clients("nova").flavors.list()
        def run(self):
            """List flavors."""
            self._list_flavors()
            self._list_flavors_as_admin()

其中,

@scenario.configure(name="ScenarioPlugin.list_flavors_useless") # 定义scenario的名字

class ListFlavors(scenario.OpenStackScenario) # 你想要继承的父类

def run(self) # 执行入口函数

@atomic.action_timer("list_flavors") # 系统的子任务,能够使用 self.context, self.admin_clients and self.clients

VerificationReporter

VerificationReporter 中定义了最后系统报告的输出格式,当前系统提供了html, json, junit-xml形式的报告,也可以自己定义report格式。

import json

from rally.verification import reporter


@reporter.configure("summary-in-json")class SummaryInJsonReporter(reporter.VerificationReporter):
    """Store summary of verification(s) in JSON format"""

    # ISO 8601
    TIME_FORMAT = "%Y-%m-%dT%H:%M:%S%z"

    @classmethod
    def validate(cls, output_destination):
        # we do not have any restrictions for destination, so nothing to
        # check
        pass

    def generate(self):
        report = {}

        for v in self.verifications:
            report[v.uuid] = {
                "started_at": v.created_at.strftime(self.TIME_FORMAT),
                "finished_at": v.updated_at.strftime(self.TIME_FORMAT),
                "status": v.status,
                "run_args": v.run_args,
                "tests_count": v.tests_count,
                "tests_duration": v.tests_duration,
                "skipped": v.skipped,
                "success": v.success,
                "expected_failures": v.expected_failures,
                "unexpected_success": v.unexpected_success,
                "failures": v.failures,
                # v.tests includes all information about launched tests,
                # but for simplification of this fake reporters, let's
                # save just names
                "launched_tests": [test["name"]
                                   for test in v.tests.values()]
            }

        raw_report = json.dumps(report, indent=4)

        if self.output_destination:
            # In case of output_destination existence report will be saved
            # to hard drive and there is nothing to print to stdout, so
            # "print" key is not used
            return {"files": {self.output_destination: raw_report},
                    "open": self.output_destination}
        else:
            # it is something that will be print at CLI layer.
            return {"print": raw_report}

Rally功能介绍

运行一个任务

以yaml格式写一个测试用例

---
{% set repeat = repeat|default(3) %}
HttpRequests.ListInstance:
{% for iteration in range(repeat) %}
- args:
    url: http://xx.xxx.xx.xxx/api/resource/listVirtualMachine
    method: POST
    status_code: 200
    json:
      pageSize: 1
      pageNumber: 1
    headers:
      Content-Type: application/json
      charset: UTF-8
  runner:
    type: constant_for_duration
    duration: 60
    concurrency: 1
  context:
    users:
      tenants: 1
      users_per_tenant: 1
  sla:
    failure_rate:
      max: 0
  hooks:
  - name: fault_injection@openstack
    args:
      action: kill mysql service on one node
    trigger:
      name: event
      args:
        unit: iteration
        at:
        - 50
{% endfor %}

运行task:

rally --plugin-paths /tmp/pycharm_project_371/rally-archos/scenarios/ListInstance.py task start --task /home/rally/data/List_Instance.yaml --deployment 4c7157d1-757e-488c-8ee4-fc976b80af58

其中,--plugin-paths参数代表了测试用例对应的代码路径,--task代表测试用例路径,--deployment代表测试环境。

运行报告

导出html报告

rally task report 8176ce9a-6c3a-473a-bb25-ac0279b04bdd --out output.html

修改报告格式

<link rel="stylesheet" href="http://cdn.bootcss.com/nvd3/1.1.15-beta/nv.d3.css">
<script type="text/javascript" src="http://cdn.bootcss.com/angular.js/1.3.3/angular.min.js">
</script>
<script type="text/javascript" src="http://cdn.bootcss.com/d3/3.4.13/d3.min.js">
</script>
<script type="text/javascript" src="http://cdn.bootcss.com/nvd3/1.1.15-beta/nv.d3.min.js">
</script>

原报告中的js被墙的关系,需要替换成国内的地址,把前缀修改成https://cdn.staticfile.org/

导出json数据

rally task report 484204c2-505c-490e-b55f-c52949802333 --json --out output.json

导出trend图

rally task trends --tasks d2aadbb1-0faf-48ee-9c2f-4184ed83eabe --out output-trends.html

生成故障分析图

rally task results 065626f2-b13d-4400-94b2-dea6644e3858 > output.json

sphinx

使用sphinx把rst转成html

pip install sphinx

Sphinx-build –b html . _build

分析故障报告

  • Recovery period:故障后服务性能下降的一段时间
  • MTTR:故障后恢复服务性能的平均时间
  • Service Downtime:服务失效时间
  • Absolute performance degradation:绝对性能下降是指恢复期间操作持续时间的平均值与基线之间的绝对差值
  • Relative performance degradation:相对性能下降—恢复期间的平均运行时间与基线之间的比率
  • Fault injection:模拟软件或硬件故障的功能
  • Service hang:模拟通过向服务进程发送SIGSTOP和SIGCONT POSIX信号来模拟挂起服务的错误
  • Service crash:通过向服务进程发送SIGKILL信号来模拟异常程序终止的故障
  • Node crash:模拟硬件意外断电的故障
  • Network partition:模拟导致运行在不同硬件节点上的服务组件之间的连接性丢失的故障;用于在HA服务中切换裂脑状态
  • Network flapping:模拟硬件节点或交换机上的网络接口断开的故障

 

 

 

0条评论
0 / 1000
丛Python
2文章数
0粉丝数
丛Python
2 文章 | 0 粉丝
丛Python
2文章数
0粉丝数
丛Python
2 文章 | 0 粉丝
原创

Rally自动化测试及plugin开发(附源码)

2023-06-27 11:43:32
66
0

Rally概述

Rally是OpenStack社区推出的开源⾃动化测试⼯具,社区希望通过Rally来解答“How does OpenStack work at scale?”的问题。为了实现这⼀⽬的,Rally集⾃动化部署、功能验证、性能测试和分析报告于⼀体。

通过使⽤ Rally 组件,⽤户可完成 OpenStack 云计算平台的安装部署、功能验证、⼤规模负载测试(性能测试)、输出测试报告等⼀系列动作,可⽤于对 OpenStack 各个组件进⾏性能测试。作为OpenStack CI/CD 系统中的基础⼯具,帮助⽤户不断提⾼系统的 SLA(服务等级协议)、性能和稳定性。

简⽽⾔之,Rally 能够帮助⽤户完成整个 OpenStack 平台或者某个单⼀组件功能的压⼒测试,帮助⽤户验证和评估稳定系统⼯作负载的规模。其中,xrally是openstack性能测试项⽬rally的⼀个新版本,当前版本下xrally以插件化的形式⽀持openstack, docker, k8s等云环境。rally将openstack的代码从他⾃身剥离出来以rally-openstack的形式存在。

https://github.com/openstack/rally.git(rally整体框架)

https://github.com/openstack/rally-openstack.git(openstack⽀持插件)

架构分析

Rally的架构图如下,展示了Rally强⼤的功能:

Rally plugin架构图, 在rally-plugin框架下:custom task scenario, runner, SLA, deployment or context都是作为⼀个plugin存在。

其中,

scenario: ⽤代码定义运⾏的场景

runner:定义运⾏周期, 并发数,运⾏次数等

SLA:对测试结果的⼀个定义

deployment:选择测试环境

context:上下⽂,初始化环境和清理环境等操作

应用场景

对于不同的使⽤场景,Rally在测试中的流程也有所不同,主要⽀持以下三种场景:

1) 开发测试,可以评估处于开发阶段的OpenStack系统的性能,能够完成安装部署、仿真测试并输出测试结果等⼀系列动作;

2) 开发运维测试,可以基于现有的OpenStack云平台,对已经安装部署的云平台进⾏仿真测试并输出测试结果;

3) CI/CD场景测试,可以将Rally集成到CI/CD系统。

以下为三种主要场景的使⽤流程:

Rally安装

自动化脚本安装

wget -q -O https://raw.githubusercontent.com/openstack/rally/master/install_rally.sh | bash

# or using curl
curl https://raw.githubusercontent.com/openstack/rally/master/install_rally.sh | bash

DevStack allinone同步安装

git clonehttps://git.openstack.org/openstack-dev/devstack
git clonehttps://github.com/openstack/rally
cd devstack
cp samples/local.conflocal.conf

编辑local.conf⽂件,在[[local|localrc]]段⾥⾯新增如下⾏:

enable_plugin rally https://github.com/openstack/rally master

执行:

./stack.sh

容器化安装

制作rally的docker镜像,以灌注⼀些其他的python lib和⾃⼰开发的代码

# 将所有⽤到的⼯具灌注到docker中制作成镜像
FROM ubuntu:16.04
RUN sed -i s/^deb-src.*// /etc/apt/sources.list
RUN apt-get update && apt-get install --yes sudo python python-pip vim git-core && \
pip install --upgrade pip && \
useradd -u 65500 -m rally && \
usermod -aG sudo rally && \
echo "rally ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/00-rally-user
COPY ./source /home/rally/source
COPY motd /etc/motd
WORKDIR /home/rally/source
# ensure that we have all system packages installed
RUN pip install bindep && apt-get install --yes $(bindep -b | tr '\n' '
')
RUN pip install -i https://pypi.douban.com/simple . --constraint upper￾constraints.txt
--ignore-installed PyYAML && \
pip install -i https://pypi.douban.com/simple pymysql --ignore-installed
PyYAML && \
pip install -i https://pypi.douban.com/simple psycopg2 --ignore￾installed PyYAML && \
pip install os-faults && \
pip install rally-runners && \
mkdir /etc/rally && \
echo "[database]" > /etc/rally/rally.conf && \
echo "connection=sqlite:////home/rally/data/rally.db" >>
/etc/rally/rally.conf
RUN echo '[ ! -z "$TERM" -a -r /etc/motd ] && cat /etc/motd' >> /etc/bash.bashrc
# Cleanup pip
RUN rm -rf /root/.cache/
USER root
ENV HOME /home/rally
RUN mkdir -p /home/rally/data && rally db recreate
RUN apt-get -y install software-properties-common && \
apt-add-repository ppa:ansible/ansible && \
apt-get update && \
apt-get install -y ansible
# Docker volumes have specific behavior that allows this construction to
work.
# Data generated during the image creation is copied to volume only when
it's
# attached for the first time (volume initialization)
VOLUME ["/home/rally/data"]

Rally plugin开发

⾸先我们需要导⼊ class: rally.task.scenario.configure ,且在 @scenario.configure(name="my_new_plugin_name") 中定义 testcase 的名字, 这⾥定义的名字将会在 yaml ⽂件中使⽤,所以2者必须完全匹配上。

from rally.task import scenario

@scenario.configure(name="my_new_plugin_name")
class MyNewPlugin(plugin.Plugin):
    pass

context

context能够在 scenario iteration开始之前执⾏初始化操作,⽐如在执⾏⼀个场景⽤例创建虚拟机之前, 需要提前准备下载Image,那就可以把download image这个操作放在context这个plugin中。context将在scenario循环开始和结束之前和之后做为⼀个处理化和清理的任务。

from rally.task import contextfrom rally.common import loggingfrom rally
import constsfrom rally.plugins.openstack import osclients

LOG = logging.getLogger(__name__)
@context.configure(name="create_flavor", order=1000)class
CreateFlavorContext(context.Context):
    """This sample creates a flavor with specified option."""
    CONFIG_SCHEMA = {
        "type": "object",
        "$schema": consts.JSON_SCHEMA,
        "additionalProperties": False,
        "properties": {
            "flavor_name": {
                "type": "string",
           },
            "ram": {
                "type": "integer",
                "minimum": 1
           },
            "vcpus": {
                "type": "integer",
                "minimum": 1
           },
            "disk": {
                "type": "integer",
                "minimum": 1
           }
       }
   }
    def setup(self):
        """This method is called before the task starts."""
        try:
            # use rally.osclients to get necessary client instance
            nova = osclients.Clients(self.context["admin"]["credential"]).nova()
            # and than do what you need with this client
            self.context["flavor"] = nova.flavors.create(
                # context settings are stored in self.config
                name=self.config.get("flavor_name", "rally_test_flavor"),
                ram=self.config.get("ram", 1),
                vcpus=self.config.get("vcpus", 1),
                disk=self.config.get("disk", 1)).to_dict()
            LOG.debug("Flavor with id '%s'" % self.context["flavor"]["id"])
        except Exception as e:
            msg = "Can't create flavor: %s" % e.message
            if logging.is_debug():
                LOG.exception(msg)
            else:
                LOG.warning(msg)
    def cleanup(self):
        """This method is called after the task finishes."""
        try:
            nova = osclients.Clients(self.context["admin"]["credential"]).nova()
            nova.flavors.delete(self.context["flavor"]["id"])
            LOG.debug("Flavor '%s' deleted" % self.context["flavor"]["id"])
        except Exception as e:
            msg = "Can't delete flavor: %s" % e.message
            if logging.is_debug():
                LOG.exception(msg)
            else:
                LOG.warning(msg)

其中,代码的写法如下图所示

@context.configure(name="create_flavor", order=1000) # 定义context的名字
class CreateFlavorContext(context.Context) # 继承context.context的⽗类
def setup(self) # 初始化操作
def cleanup(self) # 清理操作
self.context # 所有的数据需要放置到self.context这个dict中, 作为返回值
LOG = logging.getLogger(name) # 在整个rally架构中,使⽤log打印⽇志
CONFIG_SCHEMA # init to format json data**

scenario runner

scenario runner被⽤来定义scenario以⼀种什么样⼦的格式循环运⾏,共有四类:

  • constant ,⽤于通过运⾏场景固定次数来创建恒定负载,可能是并⾏的(由 “并发”参数控制)。
  • constant_for_duration,与constant完全相同,但运⾏基准场景直到经过指定的秒数(“duration”参数)。
  • rps,它以两次连续运⾏之间的间隔执⾏基准场景,在“rps”字段中以每秒次数为单位指定。
  • serial,这对于测试新场景⾮常有⽤,因为它只是在单个线程中运⾏基准场景固定次数。

此外,可以为所有场景运⾏器(再次通过配置⽂件中的“运⾏器” 部分)提供可选的“超时”参数,该参数指定每个基准场景运⾏的超时时间(以秒为单位)。

import random
from rally.task import runnerfrom rally import consts

@runner.configure(name="random_times")
class RandomTimesScenarioRunner(runner.ScenarioRunner):
    """Sample scenario runner plugin.
   Run scenario random number of times (between min_times and max_times)
  """
    CONFIG_SCHEMA = {
        "type": "object",
        "$schema": consts.JSON_SCHEMA,
        "properties": {
            "type": {
                "type": "string"
           },
            "min_times": {
                "type": "integer",
                "minimum": 1
           },
            "max_times": {
                "type": "integer",
                "minimum": 1
           }
       },
        "additionalProperties": True
   }
    def _run_scenario(self, cls, method_name, context, args):
        # runners settings are stored in self.config
        min_times = self.config.get('min_times', 1)
        max_times = self.config.get('max_times', 1)
        for i in range(random.randrange(min_times, max_times)):
            run_args = (i, cls, method_name,
                        runner._get_scenario_context(context), args)
            result = runner._run_scenario_once(run_args)
            # use self.send_result for result of each iteration
            self._send_result(result)

Hooks

测试当我们配置变更和一些基础组件重启对整个性能和稳定性的影响。在rally架构中,hooks能够模拟绝大数故障。因为我们这里需要模拟一些系统关机, 重启等操作,所以用到了一个第三方的Lib.

os-faults被用来模拟系统故障,它通过ansible脚本来控制集群。

在使用时,调用了os-faults的human-api来kill mysql process,在这里提到的action中的内容, 都需要在os-faluts.yaml中配置,而且需要将其导入至环境变量。

hooks:
  - name: fault_injection@openstack
    args:
      action: kill mysql service on one node
    trigger:
      name: event
      args:
        unit: iteration
        at:
        - 5
export OS_FAULTS_CONFIG=os-faults.yaml
cloud_management:
  driver: universal

node_discover:
  driver: node_list
  args:
  - ip: 10.xxx.xx.14
    auth:
      username: root
      password: *********
      private_key_file: cloud_key
  - ip: 10.xxx.xx.15
    auth:
      username: root
      password: *********
      private_key_file: cloud_key
  - ip: 10.xxx.xx.16
    auth:
      username: root
      password: *********
      private_key_file: cloud_key

power_managements:
- driver: ipmi
  args:
    mac_to_bmc:
      EC:38:8F:7D:40:FF:
        address: 172.xx.xx.118
        username: root
        password: *********
      E8:4D:D0:B3:CC:3D:
        address: 172.xx.xx.119
        username: root
        password: *********
      E8:4D:D0:B3:CA:D0:
        address: 172.xx.xx.120
        username: root
        password: *********

services:
  nova-api:
    driver: system_service
    args:
      service_name: nova-api
      grep: nova-api
  glance-api:
    driver: system_service
    args:
      service_name: glance-api
      grep: glance-api
  identity:
    driver: system_service
    args:
      service_name: identity
      grep: identity
  memcached:
    driver: system_service
    args:
      service_name: memcached
      grep: memcached
  mysql:                 # name of the service
    driver: process      # name of the service driver
    args:                # arguments for the driver
      grep: mysqld
      port:
      - tcp
      - 3306
      restart_cmd: sudo systemctl restart mariadb
      start_cmd: sudo systemctl start mariadb
      terminate_cmd: sudo systemctl stop mariadb
  rabbitmq-server:
    driver: system_service
    args:
      service_name: rabbitmq-server
      grep: rabbitmq-server
    hosts:
    - 172.16.170.13

scenario

context, scenario runner等plugin都是为了scenario服务的,scenario将被重复执行来验证系统的性能和稳定性。

from rally import constsfrom rally.plugins.openstack import scenariofrom rally.task import atomicfrom rally.task import validation

@validation.add("required_services", services=[consts.Service.NOVA])@validation.add("required_platform", platform="openstack", users=True)@scenario.configure(name="ScenarioPlugin.list_flavors_useless")class ListFlavors(scenario.OpenStackScenario):
    """Sample plugin which lists flavors."""

    @atomic.action_timer("list_flavors")
    def _list_flavors(self):
        """Sample of usage clients - list flavors
        You can use self.context, self.admin_clients and self.clients which are initialized on scenario instance creation"""
        self.clients("nova").flavors.list()

    @atomic.action_timer("list_flavors_as_admin")
    def _list_flavors_as_admin(self):
        """The same with admin clients"""
        self.admin_clients("nova").flavors.list()
        def run(self):
            """List flavors."""
            self._list_flavors()
            self._list_flavors_as_admin()

其中,

@scenario.configure(name="ScenarioPlugin.list_flavors_useless") # 定义scenario的名字

class ListFlavors(scenario.OpenStackScenario) # 你想要继承的父类

def run(self) # 执行入口函数

@atomic.action_timer("list_flavors") # 系统的子任务,能够使用 self.context, self.admin_clients and self.clients

VerificationReporter

VerificationReporter 中定义了最后系统报告的输出格式,当前系统提供了html, json, junit-xml形式的报告,也可以自己定义report格式。

import json

from rally.verification import reporter


@reporter.configure("summary-in-json")class SummaryInJsonReporter(reporter.VerificationReporter):
    """Store summary of verification(s) in JSON format"""

    # ISO 8601
    TIME_FORMAT = "%Y-%m-%dT%H:%M:%S%z"

    @classmethod
    def validate(cls, output_destination):
        # we do not have any restrictions for destination, so nothing to
        # check
        pass

    def generate(self):
        report = {}

        for v in self.verifications:
            report[v.uuid] = {
                "started_at": v.created_at.strftime(self.TIME_FORMAT),
                "finished_at": v.updated_at.strftime(self.TIME_FORMAT),
                "status": v.status,
                "run_args": v.run_args,
                "tests_count": v.tests_count,
                "tests_duration": v.tests_duration,
                "skipped": v.skipped,
                "success": v.success,
                "expected_failures": v.expected_failures,
                "unexpected_success": v.unexpected_success,
                "failures": v.failures,
                # v.tests includes all information about launched tests,
                # but for simplification of this fake reporters, let's
                # save just names
                "launched_tests": [test["name"]
                                   for test in v.tests.values()]
            }

        raw_report = json.dumps(report, indent=4)

        if self.output_destination:
            # In case of output_destination existence report will be saved
            # to hard drive and there is nothing to print to stdout, so
            # "print" key is not used
            return {"files": {self.output_destination: raw_report},
                    "open": self.output_destination}
        else:
            # it is something that will be print at CLI layer.
            return {"print": raw_report}

Rally功能介绍

运行一个任务

以yaml格式写一个测试用例

---
{% set repeat = repeat|default(3) %}
HttpRequests.ListInstance:
{% for iteration in range(repeat) %}
- args:
    url: http://xx.xxx.xx.xxx/api/resource/listVirtualMachine
    method: POST
    status_code: 200
    json:
      pageSize: 1
      pageNumber: 1
    headers:
      Content-Type: application/json
      charset: UTF-8
  runner:
    type: constant_for_duration
    duration: 60
    concurrency: 1
  context:
    users:
      tenants: 1
      users_per_tenant: 1
  sla:
    failure_rate:
      max: 0
  hooks:
  - name: fault_injection@openstack
    args:
      action: kill mysql service on one node
    trigger:
      name: event
      args:
        unit: iteration
        at:
        - 50
{% endfor %}

运行task:

rally --plugin-paths /tmp/pycharm_project_371/rally-archos/scenarios/ListInstance.py task start --task /home/rally/data/List_Instance.yaml --deployment 4c7157d1-757e-488c-8ee4-fc976b80af58

其中,--plugin-paths参数代表了测试用例对应的代码路径,--task代表测试用例路径,--deployment代表测试环境。

运行报告

导出html报告

rally task report 8176ce9a-6c3a-473a-bb25-ac0279b04bdd --out output.html

修改报告格式

<link rel="stylesheet" href="http://cdn.bootcss.com/nvd3/1.1.15-beta/nv.d3.css">
<script type="text/javascript" src="http://cdn.bootcss.com/angular.js/1.3.3/angular.min.js">
</script>
<script type="text/javascript" src="http://cdn.bootcss.com/d3/3.4.13/d3.min.js">
</script>
<script type="text/javascript" src="http://cdn.bootcss.com/nvd3/1.1.15-beta/nv.d3.min.js">
</script>

原报告中的js被墙的关系,需要替换成国内的地址,把前缀修改成https://cdn.staticfile.org/

导出json数据

rally task report 484204c2-505c-490e-b55f-c52949802333 --json --out output.json

导出trend图

rally task trends --tasks d2aadbb1-0faf-48ee-9c2f-4184ed83eabe --out output-trends.html

生成故障分析图

rally task results 065626f2-b13d-4400-94b2-dea6644e3858 > output.json

sphinx

使用sphinx把rst转成html

pip install sphinx

Sphinx-build –b html . _build

分析故障报告

  • Recovery period:故障后服务性能下降的一段时间
  • MTTR:故障后恢复服务性能的平均时间
  • Service Downtime:服务失效时间
  • Absolute performance degradation:绝对性能下降是指恢复期间操作持续时间的平均值与基线之间的绝对差值
  • Relative performance degradation:相对性能下降—恢复期间的平均运行时间与基线之间的比率
  • Fault injection:模拟软件或硬件故障的功能
  • Service hang:模拟通过向服务进程发送SIGSTOP和SIGCONT POSIX信号来模拟挂起服务的错误
  • Service crash:通过向服务进程发送SIGKILL信号来模拟异常程序终止的故障
  • Node crash:模拟硬件意外断电的故障
  • Network partition:模拟导致运行在不同硬件节点上的服务组件之间的连接性丢失的故障;用于在HA服务中切换裂脑状态
  • Network flapping:模拟硬件节点或交换机上的网络接口断开的故障

 

 

 

文章来自个人专栏
文章 | 订阅
0条评论
0 / 1000
请输入你的评论
0
0