蓝鲸标准插件开发

标准运维插件开发

一.准备工作

1.蓝鲸社区版环境及账号(培训方提供,不需要自己搭建)

2.蓝鲸应用开发环境(安装指南见蓝鲸开发者中心)

3.本地安装 rabbitmq、celery 和 redis

4.自己用起来顺手的 IDE,推荐 PyCharm

5.git 仓库管理工具,命令行即可

二.任务准备:创建一个蓝鲸应用

任务目标:在蓝鲸 PaaS 开发者中心,创建一个蓝鲸应用,然后在蓝鲸官网Smart 市场下载标准运维应用来初始化项目代码。

1.创建蓝鲸应用

a)创建一个代码仓库

b)打开蓝鲸开发者中心,创建一个蓝鲸应用

应用 ID:你的名字,如:bk-sops1

仓库地址:上一步中创建的 git 仓库地址

三.从git上下载源码

git地址如下https://github.com/Tencent/bk-sops

git操作步骤

从别人哪里Clone来的项目

git clone 目标项目地址git clone https://github.com/Tencent/bk-sops.git

2.进入到下载下来的项目根路径

cd bk-sops

3.删除原有的.git信息,建议sudo

sudo rm -r .git

4.初始化.git

git init

5.将本地代码添加到仓库

git add . /注意有空格

git commit -m "上传仓库时的说明"

6.关联上远程仓库

git remote add origin https://github.com/YYY/SimpleUI

此处的git地址为你自己创建的git项目地址。

7.将你的代码上传到Github

git push --set-upstream origin master

以上步骤完成之后,标准运维源码已经存放在你自己的git仓库中。

四.本地环境准备

1.本地运行准备

a)安装 python 依赖包

pip install –r requirements.txt

b)本地配置 host

c)修改项目配置

修改config/__init__.py 中下面三列,APP_ID 为你创建的应用 ID,APP_TOKEN 在应用详情中获取,BK_PAAS_HOST 为蓝鲸 PAAS 的域名。

在这里插入图片描述

修改 conf/dev.py 的本地数据库账号密码,并增加redis信息。

在这里插入图片描述

d)创建本地数据库

CREATE DATABASE `bk-sops` default charset utf8 COLLATE utf8_general_ci; 

bk-sops替换为你的应用 ID。

e)初始化数据库表

python manage.py migrate
python manage.py createcachetable django_cache

f)重启 python 和 celery 进程

python manage.py runserver 8000
python manage.py celery worker --loglevel=info

2.打包并收集前端静态资源

1)安装依赖包
进入 frontend/desktop/,执行以下命令安装

npm install

2)本地打包 在 frontend/desktop/ 目录下,继续执行以下命令打包前端静态资源

npm run build -- --STATIC_ENV=dev [--VERSION={STATIC_VERSION}]

其中 VERSION 是可选参数,建议正式打包加上该参数,{STATIC_VERSION} 是 config/default.py 中的 STATIC_VERSION 值。

3)收集静态资源 回到项目根目录,执行以下命令收集前端静态资源到 static 目录下

python manage.py collectstatic --noinput

前端资源文件需要单独拷贝收集,执行如下命令

rm -rf static/dev static/images
mv frontend/desktop/static/dev static/
mv frontend/desktop/static/images static/

3.配置本地hosts

127.0.0.1 dev.ms3.yovole.com

然后重新启动进程

python manage.py celery worker -l info # 启动异步任务时,需要用到该命令
python manage.py celery beat -l info	# 启动定时任务时,需要用到该命令
python manage.py runserver 8000	# 启动服务器

此时通过浏览器访问dev.ms3.yovole.com:8000路由可以进入到标准运维SaaS中

五.标准插件开发

1. 初始化插件模块

在项目根目录下执行 python manage.py create_atoms_app {CUSTOM PLUGINS NAME},其中 {CUSTOM PLUGINS NAME} 为你定制开发的标准插件 集合包名,注意不要和项目中已有的模块和插件集合名字重复,名字最好能体现插件包的作用。执行命令后会生成如下目录结构:

{CUSTOM PLUGINS NAME}
├── __init__.py
├── apps.py
├── components
│   ├── __init__.py
│   └── collections
│       ├── __init__.py
│       └── plugins.py
├── migrations
│   └── __init__.py
├── static
│   └── {CUSTOM PLUGINS NAME}
│       └── plugins.js
└── tests
    ├── __init__.py
    └── components
        ├── __init__.py
        └── collections
            ├── __init__.py
            └── plugins_test
                └── __init__.py

其中,components 放置标准插件集合后台代码文件,static 放置标准插件集合前端静态代码文件,plugin.pyplugin.js 可以改为你开发的标准 插件对应的系统名简称,如 job、cmdb 等。

2. 修改项目settings配置

打开 config/default.py 文件,找到INSTALLED_APPS变量,加入步骤1中创建的 {CUSTOM PLUGINS NAME}

3. 加入新的 API 网关

如果你开发的标准插件依赖自定义接入的 API 网关,那么在你将接口接入蓝鲸API网关后,需要手动将 API 添加到 Client SDK 中。 在packages/blueking/component/apis 文件下编写相应的代码即可向 Client 中添加对应的接口:

在这里插入图片描述

4. 标准插件后台开发

plugin.py 文件中编写插件后台逻辑,主要包括标准插件定义和后台执行逻辑,下面是示例代码

# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""

import logging

from packages.blueking.component.shortcuts import get_client_by_user
from django.utils import translation

from pipeline.conf import settings
from pipeline.core.flow.activity import Service
from pipeline.component_framework.component import Component
logger = logging.getLogger('celery')

from django.utils.translation import ugettext_lazy as _

# get_client_by_user = settings.ESB_GET_CLIENT_BY_USER

__group_name__ = _(u"自定义插件(CUSTOM)")


class TestCustomService(Service):
    __need_schedule__ = False

    def execute(self, data, parent_data):
        executor = parent_data.inputs.executor
        biz_cc_id = parent_data.inputs.biz_cc_id

        test_input = data.inputs.test_input
        test_textarea = data.inputs.test_textarea
        test_radio = data.inputs.test_radio
        job_task_id = data.inputs.job_task_id
        client = get_client_by_user(executor)
        if parent_data.inputs.language:
            setattr(client, 'language', parent_data.inputs.language)
            translation.activate(parent_data.inputs.language)
        api_kwargs = {
            'biz_biz_id': biz_cc_id,
            'executor': executor,
            'test_input': test_input,
            'test_textarea': test_textarea,
            'test_radio': test_radio,
            'job_task_id': job_task_id
        }

        api_result = {'result': True, 'data': {'data1': "hello world"}, 'message': "hello1"}
        print api_result
        print 'test_api result: {result}, api_kwargs: {kwargs}'.format(result=api_result, kwargs=api_kwargs)
        logger.info('test_api result: {result}, api_kwargs: {kwargs}'.format(result=api_result, kwargs=api_kwargs))
        if api_result['result']:
            data.set_outputs('data1', api_result['data']['data1'])
            return True
        else:
            data.set_outputs('ex_data', api_result['message'])
            return False

    def outputs_format(self):
        return [
            self.OutputItem(name=_(u'结果数据1'), key='data1', type='string')
        ]


class TestCustomComponent(Component):
    name = _(u"自定义插件测试")
    code = 'test_custom'
    bound_service = TestCustomService
    # embedded_form = True
    form = '%scustom_atoms/plugins.js' % settings.STATIC_URL

5. 标准插件前端开发

plugin.js 文件中编写前端逻辑,利用标准运维的前端插件框架,只需要配置就能生成前端表单,下面是示例代码

/**
* Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
* Edition) available.
* Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
(function(){
    $.atoms.test_custom = [
        {
            tag_code: "test_input",
            type: "input",
            attrs: {
                name: gettext("参数1"),
                placeholder: gettext("请输入字符串"),
                hookable: true,
                validation: [
                    {
                        type: "required"
                    }
                ]
            }
        },
        {
            tag_code: "test_textarea",
            type: "textarea",
            attrs: {
                name: gettext("参数2"),
                placeholder: gettext("多个使用换行分隔"),
                hookable: true,
                validation: [
                    {
                        type: "required"
                    }
                ]
            }
        },
        {
            tag_code: "test_radio",
            type: "radio",
            attrs: {
                name: gettext("参数3"),
                items: [
                    {value: "1", name: gettext("选项1")},
                    {value: "2", name: gettext("选项2")},
                    {value: "3", name: gettext("选项3")}
                ],
                default: "1",
                hookable: true,
                validation: [
                    {
                        type: "required"
                    }
                ]
            }
        },
         {
            tag_code: "job_task_id",
            type: "select",
            attrs: {
                name: gettext("作业模板"),
                hookable: false,
                remote: true,
                remote_url: $.context.site_url + 'pipeline/job_get_job_tasks_by_biz/' + $.context.biz_cc_id + '/',
                remote_data_init: function (resp) {
                    return resp.data;
                },
                validation: [
                    {
                        type: "required"
                    }
                ]
            }
        },
    ]
})();

6. 标准插件功能测试

开发完成后,先在根目录下执行 python manage.py collectstatic –noinput 收集静态资源。

然后新建流程模板,并添加标准插件节点,标准插件类型选择新开发的标准插件,确保展示的输入参数和前端配置项一致,输出参数和后台 outputs_format 一致,其中执行结果是系统默认,值是 TrueFalse,表示节点执行结果是成功还是失败。

重新执行以下命令

python manage.py celery worker -l info # 启动异步任务时,需要用到该命令
python manage.py celery beat -l info	# 启动定时任务时,需要用到该命令
python manage.py runserver 8000	# 启动服务器

然后使用新建的流程创建任务,填写参数并执行,执行后查看结果是否符合预期,可以结合日志更准确的评估执行结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值